组件间关系
Max Zhang Lv4

组件间关系

小程序中的组件间主要是父子组件的关系,其中便涉及到了组件间的通信。

获取组件实例

在父组件中,可以通过this.selectComponent方法获取子组件的实例。

wxml:

1
2
3
<view>
<child id="child"></child>
</view>
1
2
const child = this.selectComponent("#child");
// child 就是子组件的实例,也就是 child.js 中的 this

如果需要定制获取的组件实例

可以使用内置的behavior: wx://component-export

1
2
3
4
5
6
7
Component({
behaviors: ["wx://component-export"],
export() {
return { child: { text: "hello" } };
// 这里的 child 就是子组件的实例
},
});

父组件调用时:

1
2
const child = this.selectComponent("#child");
// child 就是{ child: { text: "hello" } }

relation

relation是组件间关系的一种方式,可以在父组件中定义relation字段,然后在子组件中定义relations字段。

父组件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
{
"usingComponents": {
"child": "./child"
},
"relations": {
"./child": {
type: "child",
linked(target) {
// target 就是子组件的实例
},
linkChanged(target) {
// target 就是子组件的实例
},
unlinked(target) {
// target 就是子组件的实例
}
}
}
}

子组件:

1
2
3
4
5
6
7
8
{
"component": true,
"relations": {
"../parent/parent": {
"type": "parent"
}
}
}

type表示关系的类型,linked表示关系建立时的回调,linkChanged表示关系变化时的回调,unlinked表示关系解除时的回调。

比如,typechild,则linked表示父组件中的child组件被添加时的回调。

 评论
评论插件加载失败
正在加载评论插件