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

vue中,组件传值的方法常见的也就那几种, 1.父组件向子组件传值,用props 属性, 2.子组件主要经过事件传递数据给父组件子向父传数据能够用$emit触发传,可是这种方法没法实现兄弟组件直接传数据 3.利用provide/inject,能够实现由祖先元素向子孙组件传递数据,方法,不须要知道祖先组件的其余做用组件,直接传递所须要的 4.利用vuex实现数据共享,把数据统一存入state, 只容许经过Actions触发Mutations修改,这种也是vue推荐的一种数据传递的方法 5.经过params 或者query,这个主要经过路由地址参数来传递值 6.借助中央事件总线(eventBus),主要运用于兄弟组件通讯 今天主要介绍eventBus实现组件通讯,这种方法主要是非父子组件,兄弟之间的组件通讯vue

EventBus 又称为事件总线。在Vue中可使用 EventBus 来做为沟通桥梁的概念,就像是全部组件共用相同的事件中心,能够向该中心注册发送事件或接收事件,因此组件均可以上下平行地通知其余组件,但也就是太方便因此若使用不慎,就会形成难以维护的灾难,所以才须要更完善的Vuex做为状态管理中心,将通知的概念上升到共享状态层次。 在本地建立目录vue-bus,在其文件下建立vue-bus.js文件。vue-router 和 Vuex 同样,给Vue添加一个属性bus, 并代理emit, on,off三个方法。 vue-bus.jsvue-router

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中使用插件vuex

import VueBus from './vue-bus'
Vue.use(VueBus)
复制代码

counter.jsbash

<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的自定义事件dom

index.vueide

<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须要注意两点:ui

  1. $bus.on应该在created钩子内使用,若是在mounted使用,它可能接收不到其余组件来自created钩子内发出的事件;
  2. 使用了bus.on,在beforeDestroy钩子里应该再使用bus.off解除,由于销毁后,就不必把监听的句柄存储在vue-bus。
相关文章
相关标签/搜索