Vue2.0进阶 - 08. 全局事件总线

Vue2.0进阶学习

vue全局事件总线

  1. 一种组件间通信的方式,适用于任意组件通信
  2. 在main.js中通过 beforeCreate(){ Vue.prototype.$bus = this; } 安装全局事件总线
  3. 主要利用的原理是 VueComponent.prototype.proto === Vue.prototype vc可以使用在vm的原型上添加的属性、方法来实现.
  4. 通信方式主要依靠自定义事件,在需要通信的双方(app.vue/student.vue)添加自定义事件和处理自定义事件.
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import Vue from 'vue';
import App from './App.vue';

Vue.config.productionTip = false;
/**
全局事件总线:
1. 一种组件间通信的方式,适用于任意组件通信
2. 在main.js中通过 beforeCreate(){ Vue.prototype.$bus = this; } 安装全局事件总线
3. 主要利用的原理是 VueComponent.prototype.__proto__ === Vue.prototype vc可以使用在vm的原型上添加的属性、方法来实现.
4. 通信方式主要依靠自定义事件,在需要通信的双方(app.vue/student.vue)添加自定义事件和处理自定义事件.
*/
new Vue({
render: (h) => h(App),
beforeCreate() {
Vue.prototype.$bus = this;
}
}).$mount('#app');
app.vue
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
<template>
<div class="dvapp">
<!--

-->
<h2>app组件</h2><br/>
<span>学生的姓名是:{{stuName}}</span><br/>
<Student ref="stu"></Student>
</div>
</template>

<script>
import Student from './components/Student.vue';
export default {
name: 'App',
data() {
return {
stuName:'',
}
},
components: {
Student
},
mounted() {
//给student添加自定义事件
this.$bus.$on('customEvent', (param) => {
this.stuName = param.name;
});
},
beforeDestroy() {
this.$bus.off('customEvent');
},
}
</script>

<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
.dvapp
{
background-color: aquamarine;
}
</style>
student.vue
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
<template>
<div class="studv">
<h2>Student组件</h2>
<span>姓名:{{stuName}}</span>
<button @click="busEventClick">通过全局事件总线触发事件传递数据</button>
</div>
</template>

<script>
export default {
data() {
return {
stuName:'odinsam-eventBus'
}
},
methods: {
busEventClick() {
console.log('function busEventClick');
this.$bus.$emit('customEvent',{name:this.stuName});
}
},
}
</script>

<style lang="css">
.studv{
background-color:bisque;
width:200px;
padding:50px;
margin-left:50px;
}
</style>

Vue2.0 基础学习目录

完整代码可以在 GitHub