这里写自定义目录标题
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");
}