在小程序中可以通过relations字段建立组件间的关系,即关联。这个关系是祖先和后代的关系。
小程序中实现组件关联的方式,主要是通过relations字段,表现形式为两种。
1、直接引用组件
子组件.png
父组件.png
必须在两个组件定义中都加入relations定义,否则不会生效。
2、关联一类组件
例如:
<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
var customFormControls = require('./custom-form-controls')
Component({
behaviors: [customFormControls],
relations: {
'./custom-form': {
type: 'ancestor', // 关联的目标节点应为祖先节点
}
}
})
// path/to/custom-submit.js
var customFormControls = require('./custom-form-controls')
Component({
behaviors: [customFormControls],
relations: {
'./custom-form': {
type: 'ancestor', // 关联的目标节点应为祖先节点
}
}
})
则在 relations 关系定义中,可使用这个behavior来代替组件路径作为关联的目标节点:
// path/to/custom-form.js
var customFormControls = require('./custom-form-controls')
Component({
relations: {
'customFormControls': {
type: 'descendant', // 关联的目标节点应为子孙节点
target: customFormControls
}
}
})
产生关联关系后,需要在有些时候获取到父组件或子组件以获取组件的数据,这时候通常使用getRelationNodes()方法获取。
获取父组件,在调用getRelationNodes时传递父组件的路径
直接引用时使用.png