Vue中全局事件总线(GlobalEventBus)
可以实现任意组件之间的互相通信
主要是通过main.js给Vue的prototype上添加一个全局事件总线,然后通过给这个对象添加自定义方法,再给各个组件之间调用this$emit和this.$on绑定和触发事件
main.js
import Vue from 'vue'
import App from './App.vue'
Vue.config.productionTip = false
new Vue({
render: (h) => h(App),
beforeCreate() {
//给Vue的prototype上添加全局事件总线
//这里的this就是vm
Vue.prototype.$bus = this
}
}).$mount('#app')
组件1
<template>
<div>
<h3>这是兄弟1组件</h3>
<button @click="fasong">点我向兄弟2发送数据</button>
</div>
</template>
<script>
export default {
data() {
return {
name: '张三'
}
},
methods: {
fasong() {
// 触发$bus上绑定的这个fasong事件,并发送一个数据
this.$bus.$emit('fasong', this.name)
}
}
}
</script>
<style></style>
组件2
<template>
<div>
<h3>这是兄弟2组件</h3>
<h3>接收到来自兄弟1数据:{{ name }}</h3>
</div>
</template>
<script>
export default {
data() {
return {
name: ''
}
},
mounted() {
// 给$bus上绑定一个fasong这个事件,并调用一个回调函数,回调函数就收一个参数,这个参数就是触发这个事件传递过来的参数
this.$bus.$on('fasong', (val) => {
this.name = val
})
}
}
</script>
<style></style>
我们在用完事件之后最好还要在销毁之前解绑这个全局的事件,如果不解绑的话,以后这个组件被销毁了,但是这个全局事件还在,就比较浪费,所以需要在销毁之前解绑这个事件,在哪个组件里面绑定的就在哪个组件里面解绑
beforeDestroy() {
// 解绑fasong这个事件
this.$bus.$off('fasong')
}