day1 eventBus

179 阅读1分钟

eventBus用法介绍

针对的是非父子组件之间的通信,它的原理还是通过事件的触发和监听

使用eventBus传递数据,我们一共需要做3件事情

  1. 给app组件添加Bus属性, 那么所有组件都可以通过this.$root.Bus访问到它
new Vue({
    // ...
    data() {
        return {
            Bus: new Vue()
        }
    }
})
  1. 在组件1里,this.root.Bus.emit触发事件
export default {
    name: 'component1',
    methods: {
        increment() {
            this.number++;
            this.$root.Bus.$emit('eventName', this.number);
        }
    }
}
  1. 在组件2里,this.root.Bus.on监听事件
export default {
    name: 'component2',
    mounted() {
        this.$root.Bus.$on('eventName', value => {
            this.number = value;
        })
    }
}

参考文章

  1. juejin.cn/post/684490…