vue eventBus事件总线

1,194 阅读1分钟

项目大了以后经常会用到状态管理或者组件传值,使用传统的方式比较麻烦,所以就有大佬发明了bus这玩意,这里总结一下。

1、首先新建一个bus.js文件,内容如下;
const install = function (Vue) {
const Bus = new Vue({
    methods:{
        //定义方法:(这里...是es6语法中的扩展运算符,不理解的小伙伴可以自行百度)
        emit(event,...args){
            this.$emit(event,...args);
        },
        on(event,callback){
            this.$on(event,callback);
        },
        off(event,callback){
            this.$off(event,callback);
        }
    }
});
//注册到给vue对象的原型上添加全局属性
Vue.prototype.$bus = Bus;
};
export default install;

2、在main.js中引入bus.js,并使用。
import Bus from './store/bus'

Vue.use(Bus)
这样就可以在组件中使用了。使用的时候需要通过this.$bus.方法(即emit,on,off),可以传递字符串,数组,函数等...

使用:
组件一:传递;
export default {
    name:'Home',
    methods:{
        init(){
            let arr1 = ['hi~'];
            function aa(){
                return arr1;
            }
            let str = 'hello';
            let arr = [2,3,4,5];
            this.$bus.$emit('log',aa())
            this.$bus.$emit('log1',str)
            this.$bus.$emit('log2',arr)
        },
    },
    created() {
        this.init();
    },
}

组件二:接收
export default {
    name:'about',
    methods:{
        change(){
            this.$bus.$emit('log',5);
        }
    },
    mounted() {
        //这里是先清空一些,据说是为了解决重复注册的问题。(不管是不是先写着吧,以防万一)
        this.$bus.$off('log')
        this.$bus.$off('log1')
        this.$bus.$off('log2')
        this.$bus.$on('log',(res)=>{
            console.log(res);
        })
        this.$bus.$on('log1',(res)=>{
            console.log(res);
        })
        this.$bus.$on('log2',(res)=>{
            console.log(res);
        })
    },
}