vue2中的一种组件通信方式,适用于任意组件间,如子孙、兄弟、父子等不同关系的组件间的通信 。
1、全局事件总线的条件
- 所有组件都能看到这个总线对象
- 这个对象能访问$emit、$on方法
因此,通常用vm对象作为全局事件总线来使用。
2、安装全局事件总线,入口文件为main.js
import Vue from 'vue'
import App from './App.vue'
Vue.config.productionTip = false
new Vue({
render: h => h(App),
// 安装全局事件总线
//$bus指向vm
beforeCreate(){
Vue.prototype.$bus = this
},
}).$mount('#app')
3、使用全局事件总线
关键:确定好接收数据的一方和提供数据的一方。
①接收数据:组件想接收数据,则在组件中给$bus绑定自定义事件,事件的回调留在组件自身。
<template>
<div class="demo">
<h2>我是Demo组件:{{sth}}</h2>
<h3>收到的数据:{{data}}</h3>
</div>
</template>
<<script>
export default {
name:'Demo',
data() {
return {
sth:'Demo的sth',
data:''
}
},
methods: {
receiveMsg(data1){
console.log('Demo组件收到数据了',data1)
this.data = data1
}
},
// 利用mounted钩子,绑定自定义事件,接收数据,收到Exam组件的数据
mounted() {
this.$bus.$on('demo',this.receiveMsg)
},
}
</script>
<style>
.demo{
color: pink;
}
</style>
②提供数据
<template>
<div class="exam">
<h2>我是Exam组件:{{msg}}</h2>
<button @click="sendMsg">点击发送数据给Demo组件</button>
</div>
</template>
<<script>
export default {
name:'Exam',
data() {
return {
msg:"Exam的msg"
}
},
methods: {
sendMsg(){
// 发送数据,触发自定义事件,将msg的内容发送给Demo组件
this.$bus.$emit('demo',this.msg)
}
},
}
</script>
<style>
.exam{
color: skyblue;
}
</style>
注:这里举的例子是兄弟关系的组件。
4、解绑事件
beforeDestroy() {
//不传参时则解绑所有自定义事件
this.$bus.$off('demo')
},
5、Vue与VueComponent的关系
VueComponent.prototype.__proto__ === Vue.prototype