# behavior
behavior 用于组件间代码共享,类似于一些编程语言中的混入 “mixin”。
behavior 可以包含一组属性、数据、方法和生命周期函数。组件引用它时,它的属性、数据和方法会被合并到组件中,生命周期函数也会在对应时机被调用。每个组件可以引用多个 behavior ,behavior 也可以引用其他的 behavior。
behavior 需要使用 Behavior 定义, 详细的参数含义和使用请参考 Behavior 参考文档。
# 组件中使用
组件引用时,在 behaviors 字段中定义用到的 behavior 数组。
代码示例:
// custom-component.js
var testBehavior = require('test-behavior')
Component({
behaviors: [testBehavior],
properties: {
testProp: {
type: String
}
},
data: {
testData: {}
},
attached: function() {},
methods: {
handleTap: function() {}
}
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 字段的覆盖和组合规则
- 同名属性或方法:组件本身的属性或方法会覆盖
behavior中的属性或方法,如果引用了多个behavior,在定义段中靠后behavior中的属性或方法会覆盖靠前的属性或方法; - 同名数据字段:如果数据是对象类型,会进行对象合并,如果是非对象类型则会进行相互覆盖;
- 生命周期函数:不会相互覆盖,而是会被逐个调用。但是如果同一个
behavior被一个组件多次引用,它定义的生命周期函数只会被执行一次。
# 内置 behaviors
快应用框架内置了两个 behavior 来方便开发者开发,分别是 'qa://form-field' 和 'qa://component-export' 。 使用是,仅需将其填入 behaviors 数组中即可。
代码示例:
Component({
behaviors: ['qa://form-field']
})
1
2
3
2
3
# qa://form-field
使自定义组件具有类似于表单控件的行为。qa://form-field 会为自定义组件添加以下两个属性,使 form 组件可以识别这些自定义组件,并在 submit 事件中返回组件的字段名及其对应字段值。
| 属性名 | 类型 | 描述 | 最低版本 |
|---|---|---|---|
| name | String | 在表单中的字段名 | |
| value | 任意 | 在表单中的字段值 |
# qa://component-export
qa://component-export 会影响 selectComponent 调用时的返回值。当使用该 behavior 时,自定义组件可以定义 export 方法,用于 selectComponent 调用时的返回。未使用这个 export 方法时, selectComponent 将返回自定义组件的实例 this。
代码示例:
// 自定义组件 test-component 内部
Component({
behaviors: ['qa://component-export'],
export() {
return { extraValue: 'value' }
}
})
1
2
3
4
5
6
7
2
3
4
5
6
7
<!-- 使用自定义组件时 -->
<test-component id="test-id" />
1
2
2
this.selectComponent('#test-id') // 等于 { extraValue: 'value' }
1
←
→
在线客服