src_全局事件总线
文章发布较早,内容可能过时,阅读注意甄别。
# 代码
# 代码路径
$ tree -N
.
├── App.vue
├── components
│ ├── School.vue
│ └── Student.vue
└── main.js
1
2
3
4
5
6
7
2
3
4
5
6
7
# App.vue
<template>
<div class="app">
<h1>{{ msg }} {{ studentName }}</h1>
<School></School>
<Student></Student>
</div>
</template>
<script>
import School from "./components/School.vue";
import Student from "./components/Student.vue";
export default {
name: "App",
components: { School, Student },
data() {
return {
msg: "你好啊!",
studentName: "",
};
},
};
</script>
<style>
.app {
background-color: gray;
}
</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
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
# School.vue
<template>
<div class="school">
<h2>学校名称:{{ name }}</h2>
<h2>学校地址:{{ address }}</h2>
</div>
</template>
<script>
export default {
name: "School",
data() {
return {
name: "shangguigua",
address: "beijing",
};
},
mounted() {
this.$bus.$on("hello", (data) => {
console.log("我是School组件,收到了数据", data);
});
},
beforeDestroy() {
this.$bus.$off("hello");
},
};
</script>
<style scoped>
.school {
background-color: blue;
}
</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
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
# Student.vue
<template>
<div class="student">
<h2>学生姓名:{{ name }}</h2>
<h2>学生性别:{{ sex }}</h2>
<button @click="sendStudentName">点我把学生名字发送给School</button>
</div>
</template>
<script>
export default {
name: "Student",
data() {
return {
name: "eryajf",
sex: "男",
number: 1,
};
},
methods: {
sendStudentName() {
this.$bus.$emit("hello", this.name);
},
},
};
</script>
<style scoped>
.student {
background-color: orange;
}
</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
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
# main.js
import Vue from "vue";
import App from "./App.vue";
Vue.config.productionTip = false;
new Vue({
el: "#app",
components: { App },
render: (h) => h(App),
beforeCreate() {
Vue.prototype.$bus = this; // 安装全局事件总线
},
});
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
# 笔记
- 一种组件间通信的方式,适用于任意组件间通信。
- 安装全局事件总线:
new Vue({
......
beforeCreate() {
Vue.prototype.$bus = this //安装全局事件总线,$bus就是当前应用的vm
},
......
})
1
2
3
4
5
6
7
2
3
4
5
6
7
- 使用事件总线:
- 接收数据:A 组件想接收数据,则在 A 组件中给
$bus
绑定自定义事件,事件的回调留在 A 组件自身。methods(){ demo(data){......} } ...... mounted() { this.$bus.$on('xxxx',this.demo) }
1
2
3
4
5
6
7 - 提供数据:
this.$bus.$emit('xxxx',数据)
- 最好在 beforeDestroy 钩子中,用$off 去解绑当前组件所用到的事件。
上次更新: 2024/11/19, 23:11:42