Vue全局事件总线
1、一种组件间通信的方式,适用于任意组件间通信。
2、安装全局事件总线
// main.js 中 安装全局事件总线 new Vue({ render: h => h(App), beforeCreate() { Vue.prototype.$bus = this // 安装全局事件总线,$bus就是当前的vue实例 } }).$mount('#app')
3、使用事件总线
(1)、接收数据:A组件想要接收数据,则在A组件中给$bus监听自定义事件,事件的回调留在A组件自身
methods: { demo(data) { } }, mounted() { this.$bus.$on('xxx',this.demo) },
(2)、提供数据
this.$bus.$emit('xxx',数据)
4、最好在beforeDestroy钩子中,用$off去解绑当前组件所用到的事件
beforeDestroy() { this.$bus.$off('xxx') }
标签:Vue,bus,总线,GlobalEventBus,事件,组件,全局 From: https://www.cnblogs.com/hyt09/p/17467135.html