微信小程序开发组件间关系
微信小程序组件间关系
1. 定义和使用组件间关系
对于复杂的自定义组件,组件之间的通讯往往比较困难。在组件定义时添加 relations 关系定义段可以解决这个问题。
示例中的 custom-ul 和 custom-li 都是自定义组件,添加如下关系定义后,它们之间的通讯就变得方便了。
// path/to/custom-ul.js
Component({
relations: {
'./custom-li': {
type: 'child', // 关联的目标节点应为子节点
linked: function(target) {
// 每次有custom-li被插入时执行,target是该节点实例对象,触发在该节点attached生命周期之后
},
linkChanged: function(target) {
// 每次有custom-li被移动后执行,target是该节点实例对象,触发在该节点moved生命周期之后
},
unlinked: function(target) {
// 每次有custom-li被移除时执行,target是该节点实例对象,触发在该节点detached生命周期之后
}
}
},
methods: {
_getAllLi: function(){
// 使用getRelationNodes可以获得nodes数组,包含所有已关联的custom-li,且是有序的
var nodes = this.getRelationNodes('path/to/custom-li')
}
},
ready: function(){
this._getAllLi()
}
})
// path/to/custom-li.js
Component({
relations: {
'./custom-ul': {
type: 'parent', // 关联的目标节点应为父节点
linked: function(target) {
// 每次被插入到custom-ul时执行,target是custom-ul节点实例对象,触发在attached生命周期之后
},
linkChanged: function(target) {
// 每次被移动后执行,target是custom-ul节点实例对象,触发在moved生命周期之后
},
unlinked: function(target) {
// 每次被移除时执行,target是custom-ul节点实例对象,触发在detached生命周期之后
}
}
}
})
注意:必须在两个组件定义中都加入relations定义,否则不会生效。
2. 关联一类组件
有时需要关联的是一类组件,这时可以使用 behavior 进行设置。对于 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', // 关联的目标节点应为祖先节点
}
}
})
在关系定义中,可以使用相同的 behavior 来代替具体的组件路径:
// path/to/custom-form.js
var customFormControls = require('./custom-form-controls')
Component({
relations: {
'customFormControls': {
type: 'descendant', // 关联的目标节点应为子孙节点
target: customFormControls
}
}
})
3. relations 定义段
relations
-
B2B2C多用户商城系统支持企业自营与商户入驻模式共存 会员一站式精细化营销工具 多用户分销,带来爆发式增长
系统支持平台自营+供应商店铺共存的经营模式(类天猫&京东模式),帮助企业打造生态级商业平台为目的的电子商务系统。
免费试用系统 -
B2B2B电商交易系统优化供应链协作 授信及账期支付 商品按照数量阶梯设价
全渠道订货/采购及经销商管理数字化系统,实现供应链整合和交易便捷化。
免费试用系统 -
S2B2B电商交易系统供销一体化,提高市场集中度 集团管控一体化,有效实现供需匹配 移动应用一体化,提高运营综合效率
上下游资源整合数字化解决方案,赋能产业供应链,构建产业互联网生态体系。
免费试用系统
