[vue2] eventBus事件总线

EventBus

eventBus(事件总线) 通常用于组件之间的信息传递 (当然vuex可以做的更好) 今天简单实现一个丐版eventBus

一、初始化

//eventBus.js


import Vue from "vue";

class Bus {
    constructor() {
        this.callbacks = {}; // 用于存储所有订阅事件
    }
    $on(name, fn) {
        this.callbacks[name] = this.callbacks[name] || [];
        this.callbacks[name].push(fn);
    }

    $emit(name, args) {
        if (this.callbacks[name]) {
            this.callbacks[name].forEach((cb) => {
                cb(args);
            });
        }
    }

    $off(name) {
        if (this.callbackes[name]) {
            delete this.callbacks[name];
        }
    }
}

function install() {
    Vue.prototype.$eventBus = new Bus();
}


export default {
    install,
};

二、main.js引入

import eventBus from "./utils/eventBus.js"; // 事件总线
Vue.use(eventBus);

三、使用


//订阅
this.$eventBus.$on("event-name", (res) => {
  console.log(res);
 });
//发布
this.$eventBus.$emit("event-name", "传递的信息");

//卸载
 this.$eventBus.$off("event-name");

四、注意点

eventBus利用发布订阅模式传递组件之间的信息,需要注意的是要在页面销毁是将注册的事件去除,否则滥用容易造成内存泄漏。

beforeDestroy(){
	this.$eventBus.$off("event-name");
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值