全局事件总线

79 阅读1分钟

全局事件总线

    作用:任意组件间进行通信。

    安装全局事件总线:
        new Vue({
            render: h => h(App),
            beforeCreate(){
                Vue.prototype.$bus = this
            }
        }).$mount('#app')
       
        原理:将vm实例对象安装到vm原型上,让所有vc都能获取到$bus,使用时通过$bus获取vm对象  
            在vm对象上进行绑定事件和触发事件,触发了的事件回调函数,会传递参数,达到传参的目的。
    
    注册和销毁自定义事件:
        mounted() {
            this.$bus.$on('hello', (data) => {
                console.log(data);
            })
        },
        beforeDestroy() {
            this.$bus.$off('hello')
        }
    
    触发自定义事件和传值:
        this.$bus.$emit('hello', 'hi,vue!')