Quasar 提供了一个全局的事件总线工具,从 Quasar v1 升级时特别有用,因为 Vue 2 中的原生事件总线接口已被移除。
方法
class EventBus {
on (event: string, callback: Function, ctx?: any): this;
once (event: string, callback: Function, ctx?: any): this;
emit (event: string, ...args: any[]): this;
off (event: string, callback?: Function): this;
}content_paste
用法
import { EventBus } from "quasar";
const bus = new EventBus();
bus.on("some-event", (arg1, arg2, arg3) => {
// do some work
});
bus.emit("some-event", "arg1 value", "arg2 value", "arg3 value");content_paste
使用 TypeScript 时,事件可以被强类型化:
// Quasar v2.11.11+
import { EventBus } from 'quasar'
const bus = new EventBus<{
'some-event': (arg1: string, arg2: string, arg3: string) => void;
'other': (arg: boolean) => void;
}>()
bus.emit('some-event', 'arg1 value', 'arg2 value', 'arg3 value')content_paste
方便的用法
在应用程序中创建一个文件,实例化并导出新的事件总线,然后在整个应用程序中导入并使用它。
或者,在 Quasar CLI 项目中,为了方便(所以不是必须的),您可以创建一个启动文件并提供一个事件总线(确保在 quasar.config file > boot 中注册它):
import { EventBus } from "quasar";
import { defineBoot } from "#q-app/wrappers";
export default defineBoot(({ app }) => {
const bus = new EventBus();
// for Options API
app.config.globalProperties.$bus = bus;
// for Composition API
app.provide("bus", bus);
});content_paste
然后,在您的任何组件中,您都可以使用:
// Options API
this.$bus;
// Composition API
import { inject } from "vue";
const bus = inject("bus"); // 在 setup() 中content_paste