JS VUE 全局的事件总线
1: 在 VUE 中各个组件相互调用,可以使用 基于 VUE 的事件总线
第一种写法:
独立的 .js
文件 比如 eventbus.js, 然后在别的 vue 或者 js 中引用
import Vue from 'vue'
export const EventBus = new Vue()
第二种写法:
以直接在项目中的 main.js
初始化 EventBus
Vue.prototype.$EventBus = new Vue()
具体使用: 分监听 和 调用 两个步骤:可以在 相同的 .vue 也可在不同的 .vue
监听:
this.EventBus.$on("decreased", ({num,deg}) => {
// Do something
});
触发:
this.EventBus.$emit("incremented", {
num:this.num,
deg:this.deg
});
2: 在 JS 中各个组件相互调用,可以使用 基于 JS 的事件总线。 由于 使用 Vue.prototype.$EventBus 的方式 具有一定的局限性 比方说 在 .js 中 就不太好 使用 .vue 所以这里 介绍另一种方式
源码: EventBus.js
(function (exporter) {
function isFunc(fn) { return typeof fn === "function" }
function str(s) {
if (s == null) {
return null;
}
s = s.replace(/^\s+|\s+$/g, "");
return s.length > 0 ? s.toLowerCase() : null;
}
function handler() {
var fns = [];
var datas = [];
this.add = function (fn, data) {
fns.push(fn);
datas.push(data);
}
this.remove = function (fn) {
var i = fns.indexOf(fn);
if (i >= 0) {
fns.splice(i, 1);
datas.splice(i, 1);
}
}
this.invoke = function (sender, data) {
fns.forEach((fn, i) => {
try {
fn(sender, data, datas[i])
} catch (error) {
console.error(error);
}
});
}
}
function eventBus() {
var handers = {}
this.on = function (eventName, fnOrData, fn) {
eventName = str(eventName);
if (eventName == null) {
throw new Error("事件名无效");
}
if (!isFunc(fn)) {
var temp = fn;
fn = fnOrData;
fnOrData = temp;
}
if (!isFunc(fn)) {
throw new Error("必须提供事件函数");
}
var handle = handers[eventName];
if (handle == null) {
handle = new handler();
handers[eventName] = handle;
}
handle.add(fn, fnOrData);
}
this.off = function (eventName, fn) {
eventName = str(eventName);
if (eventName == null) {
return;
}
var handle = handers[eventName];
if (handle != null) {
if (fn == null) {
delete handers[eventName];
} else {
handle.remove(fn);
}
}
}
this.fire = this.emit = this.trigger =
function (eventName, sender, data) {
eventName = str(eventName);
if (eventName == null) {
return;
}
var handle = handers[eventName];
if (handle != null) {
handle.invoke(sender, data);
}
}
var bus = this;
this.bindTo = function(obj){
if(obj == null){
throw new Error("obj is null");
}
for (const key in bus) {
if (bus.hasOwnProperty(key) && key !== "bindTo") {
obj[key] = bus[key];
}
}
}
}
var instance = new eventBus();
instance.bindTo(eventBus);
exporter(eventBus);
})(c => window.eventBus = c)
你可以在 main.js
引入一下 就可以全局使用了