gpt4 book ai didi

vue.js - 如何在 Vue 3 上创建本地事件总线

转载 作者:行者123 更新时间:2023-12-04 12:19:13 28 4
gpt4 key购买 nike

如何在一页上使用事件总线,以便所有组件和页面都可以在那里读取和接收事件
例如,在 vue 2 中,我创建了一个对象,该对象在创建页面时为具有上下文的字段分配,并且我在页面的所有组件中使用了此上下文
例子

//main.js
global.context = new Object();
global.context.app = Vue;

//field assignment with context
global.context.authorization = this;

//using context
global.context.authorization.$emit(
"authorizationMessage",
this.t("Password fields didn't match")
);

我可以使用导入来改进这种方法吗?
在 vue 3 中,我使用时遇到错误
global.context.authorization.$on("authorizationMessage", (msg) => {
alert(msg);
});
Uncaught (in promise) TypeError: global.context.authorization.$on is not a function
at Proxy.created (Messenger.vue?1b1a:25)
at callWithErrorHandling (runtime-core.esm-bundler.js?5c40:154)
at callWithAsyncErrorHandling (runtime-core.esm-bundler.js?5c40:163)
at callHookWithMixinAndExtends (runtime-core.esm-bundler.js?5c40:6032)
at callSyncHook (runtime-core.esm-bundler.js?5c40:6018)
at applyOptions (runtime-core.esm-bundler.js?5c40:5956)
at finishComponentSetup (runtime-core.esm-bundler.js?5c40:6636)
at setupStatefulComponent (runtime-core.esm-bundler.js?5c40:6567)
at setupComponent (runtime-core.esm-bundler.js?5c40:6503)
at mountComponent (runtime-core.esm-bundler.js?5c40:4206)

最佳答案

关注 Vue 3 migration guide for using Vue as an event bus ,用 tiny-emitter 的实例替换该总线:

// event-bus.js
import emitter from 'tiny-emitter/instance'

export default {
$on: (...args) => emitter.on(...args),
$once: (...args) => emitter.once(...args),
$off: (...args) => emitter.off(...args),
$emit: (...args) => emitter.emit(...args),
}
并像这样使用它:
// main.js
import eventBus from './event-bus'

//...
global.context.authorization = eventBus
demo

关于vue.js - 如何在 Vue 3 上创建本地事件总线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68056880/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com