wepy提供了$broadcast$emit$invoke三个方法来为我们实现page和子组件或者组件和组件之间的通信。

$broadcast

page通过$broadcast方法向所有被引用的组件发送指定广播,子组件如果有需要则在events里面设置接收器用来接收page的广播,然后进行相应的事件处理。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
<!-- page -->
<view @tap="changeText">
<comA />
<comB />
</view>

<script>
import wepy from 'wepy';
import ComA from 'components/coma';
import ComB from 'components/comb';
export default class Index extends wepy.page {
components = {
comA: ComA,
comB: ComB
};
methods = {
changeText() {
this.$broadcast('com-changeText');
}
};
}
</script>

<!-- comA -->
<view>{{text}}</view>

<script>
import wepy from 'wepy';
export default class ComA extends wepy.component {
data = {
text: 'comA'
};
events = {
'com-changeText': () => {
this.text = 'comA接收到来自父级broadcast的变更';
this.$apply();
}
};
}
</script>

<!-- comB -->
<view>{{text}}</view>

<script>
import wepy from 'wepy';
export default class ComB extends wepy.component {
data = {
text: 'comB'
};
events = {
'com-changeText': () => {
this.text = 'comA接收到来自父级broadcast的变更';
this.$apply();
}
};
}
</script>

$emit

emit和broadcast正好相反,由子组件向所有其父组件发送消息,只有当父组件的 events 内设置了接收方法才会相应来自子组件的广播消息并处理对应的事件。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<!-- page -->
<view>
<text>{{text}}</text>
<comA />
</view>

<script>
import wepy from 'wepy';
import ComA from 'components/coma';
export default class Index extends wepy.page {
data = {
text: '父级初始化内容'
};
components = {
comA: ComA
};
events = {
changeText: (txt) => {
this.text = txt;
this.$apply();
}
};
}
</script>

<!-- comA -->
<view @tap="changeText">comA</view>

<script>
import wepy from 'wepy';
export default class ComA extends wepy.component {
methods = {
changeText() {
this.$emit('changeText', '我就要你变');
}
}
}
</script>

$invoke

invoke可以理解成直接使用:page或者子组件可以直接拿到page或者子组件中methods内定义的方法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<!-- page -->
<view>
<text @tap="getComaText">点我改变comA的内容</text>
<comA />
</view>

<script>
import wepy from 'wepy';
import ComA from 'componnets/coma';
export default class Index extends wepy.page {
components = {
comA: ComA
};
methods = {
getComaText() {
this.$invoke('comA', 'changeText', '父级通过invoke改变子组件内容'); // 第一个参数为组件,第二个参数为调用的组件的某个方法,第三个参数为真正的传参
}
};
}
</script>

<!-- comA -->
<view>{{content}}</view>

<script>
import wepy from 'wepy';
export default class ComA extends wepy.component {
data = {
content: '初始化子内容'
};
methods = {
changeText(txt) {
this.content = txt;
this.$apply();
}
};
}
</script>

在组件通信中,一定要理解所调用的方法是在哪个里面定义的:broadcash、emit所处理的事件需要在 events里面定义,如果emit调用的是自定义事件,则自定义事件需要在 methods 里面有定义。而invoke是直接调用methods里面的方法。