全局事件总线(GlobalEventBus)

suaxi
2022-07-17 / 0 评论 / 43 阅读 / 正在检测是否收录...
  1. 定义:一种组件间的通信方式,适用于任意组件间通信
  2. 安装全局事件总线

    new Vue({
        ......
        beforeCreate() {
            //安装全局事件总线
            Vue.prototype.$bus = this
        }
    })
  3. 使用:

    (1)接收数据:

    A组件想接收数据,则在A组件中给$bus绑定自定义事件,且回调留在A组件自身

    methods: {
        demo(data) {
            ......
        }
    }
    
    mounted() {
        this.$bus.$on('xxx', this.demo)
    }

    (2)提供数据:

    this.$bus.$emit('xxx', data)
  4. 注:最好在beforeDestroy钩子函数中,使用$off('xxx')解绑当前组件所用到的自定义事件
0

评论 (0)

取消