写一个eventBus.js:
export default class eventBus{
constructor() {
this.events = {};
}
on(eventName, callback) {
if (typeof callback !== "function") {
throw "请传入监听函数";
}
if (!this.events[eventName]) {
this.events[eventName] = [];
}
this.events[eventName].push(callback);
}
emit(eventName, ...args) {
if (this.events[eventName]) {
this.events[eventName].forEach((cb) => {
cb.call(this, ...args);
});
}
}
off(eventName, callback) {
if (this.events[eventName]) {
if (callback) {
var index = this.events[eventName].indexOf(callback);
if (index > -1) {
this.events[eventName].splice(index, 1);
}
} else {
this.events[eventName].length = 0;
}
}
}
}
main.js引入eventBus ,全局挂载$Bus实例:
import eventBus from "@/utils/eventBus";
Vue.prototype.$Bus= new eventBus();
vue组件内使用示例:
//监听事件
this.$Bus.on("pageA/upload", () => {
this.show = true;
});
//触发事件
this.$Bus.emit("pageA/upload", true);
//卸载事件
this.$Bus.off("pageA/upload");