vue eventBus事件总线

项目大了以后经常会用到状态管理或者组件传值,使用传统的方式比较麻烦,所以就有大佬发明了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);
        })
    },
}复制代码

转载于:https://juejin.im/post/5c418635f265da611d66ebe2

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值