Vue多个子组件的EventBus


title: Vue多个子组件的EventBus
date: 2018-11-23 17:27:03
tags: [Vue]
categories: Vue


前言

我在 轱辘UI 项目做 tabs 组件时,该组件有父子组件通讯的需求,然而多个子组件之间怎么通讯呢?我了解到可以用 EventBus 结合 依赖注入 来解决。

什么是EventBus

即组件共用的事件中心,可以向该中心注册发送事件或接收事件,所以组件都可以上下平行地通知其他组件。

如何在父子组件中使用EventBus

父组件:

export default {
    data(){
        return {
            eventBus: new Vue()
        }
    },
    provide() {
        return {
            eventBus: this.eventBus
        }
    },
    mounted() {
        this.eventBus.$emit('event', () => {

        })
    }
}

所有后代组件:

export default {
    inject: ['eventBus'],
    mounted() {
        this.eventBus.$on('event', () => {

        })
    }
}

其实就是用一个新的Vue实例的 on 和 $off 这三个接口来达到一个 EventBus 的效果

更多可见我的 tabs组件 相关代码

你可能感兴趣的:(Vue多个子组件的EventBus)