实现非父子之间通信,兄弟组件之间的数据传递--eventBus

转载:https://www.jianshu.com/p/f866c8ac4d02

vue中,组件传值的方法常见的也就那几种:

1.父组件向子组件传值,用props 属性,
2.子组件主要通过事件传递数据给父组件子向父传数据可以用$emit触发传,但是这种方法无法实现兄弟组件直接传数据
3.利用provide/inject,可以实现由祖先元素向子孙组件传递数据,方法,不需要知道祖先组件的其他作用组件,直接传递所需要的
4.利用vuex实现数据共享,把数据统一存入state, 只允许通过Actions触发Mutations修改,这种也是vue推荐的一种数据传递的方法
5.通过params 或者query,这个主要通过路由地址参数来传递值
6.借助中央事件总线(eventBus),主要运用于兄弟组件通信 今天主要介绍eventBus实现组件通信,这种方法主要是非父子组件,兄弟之间的组件通信
 
EventBus 又称为事件总线。在Vue中可以使用 EventBus 来作为沟通桥梁的概念,就像是所有组件共用相同的事件中心,可以向该中心注册发送事件或接收事件,所以组件都可以上下平行地通知其他组件,但也就是太方便所以若使用不慎,就会造成难以维护的灾难,因此才需要更完善的Vuex作为状态管理中心,将通知的概念上升到共享状态层次。
在本地创建目录vue-bus,在其文件下创建vue-bus.js文件。vue-router 和 Vuex 一样,给Vue添加一个属性bus并代理,emit,on,off三个方法。

vue-bus.js

const install = function (Vue) {
    const Bus = new Vue({
        methods: {
            emit (event, ...args) {
                this.$emit(event, ...args);
            },
            on (event, callback) {
                this.$on(event, callback);
            },
            off (event, callback) {
                this.$off(event, callback);
            }
        }
    });
    Vue.prototype.$bus = Bus;
};

export default install;

在mainjs中使用插件

import VueBus from './vue-bus'
Vue.use(VueBus)

counter.vue

<template>
    <div>
        {{ number }}
        <button @click="handleAddRandom">随机增加</button>
    </div>
</template>
<script>
    export default {
        props: {
            number: {
                type: Number
            }
        },
        methods: {
            handleAddRandom () {
                // 随机获取 1-100 中的数
                const num = Math.floor(Math.random () * 100 + 1);
                this.$bus.emit('add', num);
            }
        }
    };
</script>

在index.vue 中使用counter组件并监听来自counter.vue的自定义事件

index.vue

<template>
    <div>
        <h1>首页</h1>
        随机增加:
        <Counter :number="number"></Counter>
    </div>
</template>
<script>
    import Counter from './counter.vue';
    export default {
        components: {
            Counter
        },
        data () {
            return {
                number: 0
            }
        },
        methods: {
        handleAddRandom (num) {
                this.number += num;
            }
    },
        created () {
            this.$bus.on('add', this.handleAddRandom);
        },
        beforeDestroy () {
            this.$bus.off('add', this.handleAddRandom);
        }
    }
</script>

vue-bus的代码比较简单,但它却解决来跨组件直接的通信问题,而且通过插件的形式使用后,所有的组件都可以使用$bus,而无须每个组件导入bus组件,

使用vue-bus需要注意两点:

  1. $bus.on应该在created钩子内使用,如果在mounted使用,它可能接收不到其他组件来自created钩子内发出的事件;
  2. 使用了bus.on,在beforeDestroy钩子里应该再使用 bus.off解除,因为销毁后,就没必要把监听的句柄存储在vue-bus。
posted @ 2020-01-15 17:11  一抹夏忧☆  阅读(935)  评论(0编辑  收藏  举报