# 组件间通信与事件
可遵循 vue 规范
# this.$emit
触发全局的自定义事件。附加参数都会传给监听器回调。
属性 | 类型 | 描述 |
---|---|---|
eventName | String | 事件名 |
OBJECT | Object | 触发事件携带的附加参数 |
代码示例
this.$emit("update", { msg: "页面更新" });
1
# this.$on
监听全局的自定义事件。事件可以由 this.$emit 触发,回调函数会接收所有传入事件触发函数的额外参数。
属性 | 类型 | 描述 |
---|---|---|
eventName | String | 事件名 |
callback | Function | 事件的回调函数 |
代码示例
this.$on("update", function (data) {
console.log("监听到事件来自 update ,携带参数 msg 为:" + data.msg);
});
1
2
3
2
3
# this.$once
监听全局的自定义事件。事件可以由 this.$emit 触发,但是只触发一次,在第一次触发之后移除监听器。
属性 | 类型 | 描述 |
---|---|---|
eventName | String | 事件名 |
callback | Function | 事件的回调函数 |
代码示例
this.$once("update", function (data) {
console.log("监听到事件来自 update ,携带参数 msg 为:" + data.msg);
});
1
2
3
2
3
# this.$off
移除全局自定义事件监听器。
属性 | 类型 | 描述 |
---|---|---|
eventName | Array<String> | 事件名 |
callback | Function | 事件的回调函数 |
Tips
- 如果没有提供参数,则移除所有的事件监听器;
- 如果只提供了事件,则移除该事件所有的监听器;
- 如果同时提供了事件与回调,则只移除这个回调的监听器;
- 提供的回调必须跟 $on 的回调为同一个才能移除这个回调的监听器;
代码示例
$emit
、$on
、$off
常用于跨页面、跨组件通讯,这里为了方便演示放在同一个页面
<template>
<view class="content">
<view class="data">
<text>{{ val }}</text>
</view>
<button type="primary" @click="comkzcationOff">结束监听</button>
</view>
</template>
<script>
export default {
data() {
return {
val: 0,
};
},
onLoad() {
setInterval(() => {
this.$emit("add", {
data: 2,
});
}, 1000);
this.$on("add", this.add);
},
methods: {
comkzcationOff() {
this.$off("add", this.add);
},
add(e) {
this.val += e.data;
},
},
};
</script>
<style>
.content {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.data {
text-align: center;
line-height: 40px;
margin-top: 40px;
}
button {
width: 200px;
margin: 20px 0;
}
</style>
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
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