1.封装的方法:
ZJeventCenter.js
!(function (window) { if ("ZJeventCenter" in window && window.ZJeventCenter) return; window.ZJeventCenter = { list: [], on (event, fn) { (this.list[event] || (this.list[event] = [])).push(fn); return this; }, once (event, fn) { const _this = this; function on () { _this.off(event, on); fn.apply(_this, arguments); } on.fn = fn; this.on(event, on); return this; }, off (event, fn) { let fns = this.list[event]; if (!fns) return false; if (!fn) { fns && (fns.length = 0); } else { let cb = null; for (let i = 0; i < fns.length; i++) { cb = fn[i]; if (cb === fn || cb.fn === fn) { fns.splice(i, 1); break; } } } return; }, emit () { let event = [].shift.call(arguments); let fns = [...this.list[event]]; if (!fns || fns.length === 0) { return false; } fns.forEach((fn) => { fn.apply(this, arguments); }); return this; }, }; })(window);
2.在App.vue中引入
import "@/utils/ZJeventCenter.js"
3.在HomeView.vue页面注册方法
mounted () { // 注册num方法 window.ZJeventCenter.on('num', this.num) }, methods: { // mum方法 num (data) { let num1 = data.a + data.b; console.log(num1); } }
4.在AboutView.vue页面使用方法
<button @click="fn">a+b</button>
fn () { window.ZJeventCenter.emit("num", { a: 1, b: 1 }); }