// 引入 Vue 3
import { createApp, reactive } from 'vue';
// 创建一个全局事件总线
const bus = {
install(app) {
const eventBus = reactive({ events: {} });
app.config.globalProperties.$bus = {
$on(event, callback) {
if (!eventBus.events[event]) {
eventBus.events[event] = [];
}
eventBus.events[event].push(callback);
},
$off(event, callback) {
if (eventBus.events[event]) {
const index = eventBus.events[event].findIndex(cb => cb === callback);
if (index !== -1) {
eventBus.events[event].splice(index, 1);
}
}
},
$emit(event, ...args) {
if (eventBus.events[event]) {
eventBus.events[event].forEach(callback => callback(...args));
}
}
};
app.provide('bus', app.config.globalProperties.$bus);
}
};
// 创建 Vue 应用并使用事件总线插件
const app = createApp({
setup() {
// 使用 provide 接收事件总线
const bus = inject('bus');
return {
bus
};
}
});
app.use(bus);
app.mount('#app');
创建全局事件总线:
bus
对象,它包含 $on
, $off
, 和 $emit
方法,用于订阅、取消订阅和触发事件。reactive
来创建一个响应式的 events
对象,用于存储事件及其对应的回调函数。安装插件:
install
方法将事件总线挂载到 Vue 应用的 globalProperties
中,并通过 provide
提供给子组件使用。使用事件总线:
setup
函数中,我们通过 inject
获取事件总线实例,并将其返回以便在模板中使用。挂载应用:
#app
元素。这样,你就可以在 Vue 3 项目中使用这个全局事件总线来进行组件间的通信了。
上一篇:vue2监听props数据变化
下一篇:vue3 .sync
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站