抖音开放平台Logo
开发者文档
“/”唤起搜索
控制台

组件间关系
收藏
我的收藏

定义和使用组件间关系

有时需要实现这样的功能:
<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 的组件节点都会被关联