Vue 兄弟组件通信之事件总线

327 阅读1分钟

场景:

同一个页面有多个组件需要进行交互时,不想使用store,可以使用

功能

监听组件之间的事件

代码

在main.js中添加

// 添加事件总线
Vue.prototype.$bus = new Vue();

使用

组件A 在某个函数中使用

this.$bus.$emit("say", 'HELLO');

组件B 在created生命周期中添加监听

created () {
    this.$bus.$on("say", (str) => {
        console.log(str) // 'HELLO'
    })
},

对你有帮助的话点个赞哦