如何在 Vue 3 中创建事件总线?
在 Vue 2 中,它是:
export const bus = new Vue();
bus.$on(...) bus.$emit(...)
在 Vue 3 中,Vue 不再是构造函数,并且 Vue.createApp({}); 返回一个没有 $on 的对象 code> 和 $emit 方法。
Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
在 Vue.js 版本 3 上,您可以使用第三方库,也可以使用以发布者-订阅者(PubSub 概念)编程模式编写的功能。
事件.js
//events - a super-basic Javascript (publish subscribe) pattern class Event{ constructor(){ this.events = {}; } on(eventName, fn) { this.events[eventName] = this.events[eventName] || []; this.events[eventName].push(fn); } off(eventName, fn) { if (this.events[eventName]) { for (var i = 0; i < this.events[eventName].length; i++) { if (this.events[eventName][i] === fn) { this.events[eventName].splice(i, 1); break; } }; } } trigger(eventName, data) { if (this.events[eventName]) { this.events[eventName].forEach(function(fn) { fn(data); }); } } } export default new Event();index.js
import Vue from 'vue'; import $bus from '.../event.js'; const app = Vue.createApp({}) app.config.globalProperties.$bus = $bus;