1.组件之间使用behavior
定义和使用 behaviors
behaviors 是用于组件间代码共享的特性。也就是组件能继承behavior的方法和属性。
每个 behavior 可以包含一组属性、数据、生命周期函数和方法,组件引用它时,它的属性、数据和方法会被合并到组件中,生命周期函数也会在对应时机被调用。每个组件可以引用多个 behavior 。behavior 也可以引用其他 behavior.
// my-behavior.js
module.exports = Behavior({
behaviors: [],
properties: {
myBehaviorProperty: {
type: String
}
},
data: {
myBehaviorData: {}
},
attached() {},
methods: {
myBehaviorMethod() {}
}
})
组件引用时,在 behaviors 定义段中将它们逐个列出即可。
// my-component.js
const myBehavior = require('my-behavior')
Component({
behaviors: [myBehavior],
properties: {
myProperty: {
type: String
}
},
data: {
myData: {}
},
attached() {},
methods: {
myMethod() {}
}
})
2.组件之间的通讯
有时需要实现这样的组件:
<custom-ul>
<custom-li>item 1</custom-li>
<custom-li>item 2</custom-li>
</custom-ul>
使用relations 定义段, 解决custom-ul 和 custom-li 都是自定义组件之间通讯的问题。示例:
// path/to/custom-ul.js
Component({
relations: {
'./custom-li': {
type: 'child', // 关联的目标节点应为子节点
linked(target) { //这个应该是自定义组件的生命周期
// 每次有custom-li被插入时执行,target是该节点实例对象,触发在该节点attached生命周期之后
},
linkChanged(target) {
// 每次有custom-li被移动后执行,target是该节点实例对象,触发在该节点moved生命周期之后
},
unlinked(target) {
// 每次有custom-li被移除时执行,target是该节点实例对象,触发在该节点detached生命周期之后
}
}
},
methods: {
_getAllLi() {
// 使用getRelationNodes可以获得nodes数组,包含所有已关联的custom-li,且是有序的
const nodes = this.getRelationNodes('path/to/custom-li')
}
},
ready() {
this._getAllLi()
}
})
// path/to/custom-li.js
Component({
relations: {
'./custom-ul': {
type: 'parent', // 关联的目标节点应为父节点
linked(target) {
// 每次被插入到custom-ul时执行,target是custom-ul节点实例对象,触发在attached生命周期之后
},
linkChanged(target) {
// 每次被移动后执行,target是custom-ul节点实例对象,触发在moved生命周期之后
},
unlinked(target) {
// 每次被移除时执行,target是custom-ul节点实例对象,触发在detached生命周期之后
}
}
}
})
注意:必须在两个组件定义中都加入relations定义,否则不会生效。
3.关联一类组件,然后进行通讯
如:
<custom-form>
<view>
input
<custom-input></custom-input>
</view>
<custom-submit>submit</custom-submit>
</custom-form>
custom-form 组件想要关联 custom-input 和 custom-submit 两个组件。此时,如果这两个组件都有同一个behavior:
// path/to/custom-form-controls.js
module.exports = Behavior({
// ...
})
// path/to/custom-input.js
const customFormControls = require('./custom-form-controls')
Component({
behaviors: [customFormControls],
relations: {
'./custom-form': { //子组件关联父组件
type: 'ancestor', // 关联的目标节点应为祖先节点
}
}
})
// path/to/custom-submit.js
const customFormControls = require('./custom-form-controls')
Component({
behaviors: [customFormControls],
relations: {
'./custom-form': { //子组件关联父组件
type: 'ancestor', // 关联的目标节点应为祖先节点
}
}
})
则在 relations 关系定义中,可使用这个behavior来代替组件路径作为关联的目标节点:
// path/to/custom-form.js
const customFormControls = require('./custom-form-controls')
Component({
relations: {
customFormControls: {
type: 'descendant', // 关联的目标节点应为子孙节点
target: customFormControls //
}
}
})