Vue组件间通信-全局时间总线

353 阅读1分钟
  1. 作用:用于任意组件间通信
  2. 安装全局事件总线:
new Vue({
    render: h => h(App),
    beforeCreate() {
        // 安装全局事件总线
        Vue.prototype.$bus = this
    }
}).$mount('#app')
  1. 使用全局时间总线
    3.1 接收数据:A组件想接收数据,则在A组件中给$bus绑定自定义事件,事件的回调留在A组件自身,绑定的事件名称不能重复
    methods: {
        demo(name) {
            // 通过$bus收到的数据
            console.log('收到的name是:', name);
        }
    }
    
    mounted() {
        // 给全局时间总线绑定hello事件 事件回调是demo方法
        this.$bus.$on('hello', this.demo)
    }
    
    
  2. 最好在beforeDestory钩子中,用$off解绑当前组件中用到的事件