Quasar 提供全局 EventBus,在从 Quasar v1 升级(原生 Vue 2 接口已被移除)时尤其有用。
¥Quasar supplies a global EventBus, especially useful when upgrading from Quasar v1 where the native Vue 2 interface has been dropped.
方法(Methods)
¥Methods
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;
}
用法(Usage)
¥Usage
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')
使用 TypeScript 时,事件可以是强类型的:
¥When using TypeScript the events can be strongly-typed:
// 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')
便捷用法(Convenience usage)
¥Convenience usage
在应用中创建一个文件,用于实例化和导出新的事件总线,然后导入并在整个应用中使用它。
¥Create a file in your app where you instantiate and export the new event bus then import and use it throughout your app.
或者,在 Quasar CLI 项目中,为了方便起见(因此不是必需的),你可以创建一个启动文件并提供一个事件总线(请确保在 quasar.config 文件 > boot 中注册它):
¥Alternatively, when on a Quasar CLI project, for your convenience (so NOT required) you can create a boot file and supply an event bus (make sure that you register it in 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)
})
然后,在你的任何组件中,你都可以使用:
¥Then, in any of your components, you can use:
// Options API
this.$bus
// Composition API
import { inject } from 'vue'
const bus = inject('bus') // inside setup()