组件间关系
收藏我的收藏
定义和使用组件间关系
有时需要实现这样的功能:
<custom-ul> <custom-li>item 1</custom-li> <custom-li>item 2</custom-li> </custom-ul>
多层级自定义组件需要互相通信,实现起来比较复杂,这个时候可以使用
relations
字段解决。// path/to/custom-ul.js Component({ relations: { "./custom-li": { type: "child", // 关联目标节点应该为子节点 linked(target) { // 每次有 custom-li 被插入时执行,target 是该节点实例对象,触发在该节点 attached 生命周期之后 }, unlinked(target) { // 每次有 custom-li 被移除时执行,target 是该节点实例对象,触发在该节点 detached 生命周期之后 }, }, }, methods: { _getAllLi() { // 使用 getRelationNodes 可以获得 nodes 数组,包含所有已关联的 custom-li,且是有序的 this.getRelationNodes("path/to/custom-li", (nodes) => {}); }, }, ready() { this._getAllLi(); }, });
// path/to/custom-li.js Component({ relations: { "./custom-ul": { type: "parent", // 关联的目标节点应为父节点 linked(target) { // 每次被插入到 custom-ul 时执行,target是 custom-ul 节点实例对象,触发在 attached 生命周期之后 }, unlinked(target) { // 每次被移除时执行,target是 custom-ul 节点实例对象,触发在 detached 生命周期之后 }, }, }, });
注意
必须在两个组件定义中都加入 relations 定义,否则不会生效。
relations 定义段
relations
定义段包含目标组件路径及其对应选项,可包含的选项见下表。属性 | 类型 | 是否必填 | 描述 |
type | String | 是 | 目标组件的相对关系,可选的值为 parent 、 child 、 ancestor 、 descendant |
linked | Function | 否 | 关系生命周期函数,当关系被建立在页面节点树中时触发,触发时机在组件 attached 生命周期之后 |
unlinked | Function | 否 | 关系生命周期函数,当关系脱离页面节点树时触发,触发时机在组件 detached 生命周期之后 |
target | String | 否 | 如果这一项被设置,则它表示关联的目标节点所应具有的 behavior,所有拥有这一 behavior 的组件节点都会被关联 |
getRelationNodes
获取这个关系所对应的所有关联节点。
语法
component.getRelationNodes(path, callback)
参数说明
path
类型 | 默认值 | 必填 | 说明 | 最低支持版本 |
string | | 是 | 关联组件的路径 | 1.0.0 |
callback
类型 | 默认值 | 必填 | 说明 | 最低支持版本 |
function | | 否 | 监听消息的回调函数 | 1.0.0 |
回调函数参数说明
callback 返回组件实例
返回值
无