This repository has been archived by the owner on May 4, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
8-兄弟组件间数据通信.html
88 lines (85 loc) · 2.41 KB
/
8-兄弟组件间数据通信.html
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<script src="./lib/vue.js"></script>
</head>
<body>
<div id="app">
{{msg}}<br />
<button @click="clearEvent">清除事件:</button>
<tom-component></tom-component>
<jerry-component></jerry-component>
</div>
<script>
// 兄弟组件之间数据通信
// 1. 定义一个全局的 Vue 实例,担任全局事件中心
var event_hub = new Vue();
Vue.component("tom-component", {
data: function() {
return {
count: 0,
};
},
template: `
<div>
TOM:{{count}}<br/>
<button @click="handle">点击</button>
</div>
`,
methods: {
handle: function() {
// 触发jerry的函数
event_hub.$emit("jerry-event", 1);
},
},
mounted: function() {
// 监听事件
event_hub.$on("tom-event", (val) => {
this.count += val;
});
},
});
Vue.component("jerry-component", {
data: function() {
return {
count: 0,
};
},
template: `
<div>
JERRY:{{count}}<br/>
<button @click="handle">点击</button>
</div>
`,
methods: {
handle: function() {
// 触发对方的事件
event_hub.$emit("tom-event", 2);
},
},
mounted: function() {
// 自己也创建一个
event_hub.$on("jerry-event", (val) => {
this.count += val;
});
},
});
const vm = new Vue({
el: "#app",
data: {
msg: "父组件信息",
},
methods: {
clearEvent: function() {
event_hub.$off("tom-event");
event_hub.$off("jerry-event");
},
},
});
</script>
</body>
</html>