為何捐款
API 瀏覽器
EventBus 工具程式
v2.8.4+

Quasar 提供了一個全域 EventBus,在從 Quasar v1 升級時特別有用,因為在 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;
}

用法

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 時,事件可以是強型別的

// 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')

便捷用法

在您的應用程式中建立一個檔案,您可以在其中實例化並匯出新的 event bus,然後在您的整個應用程式中匯入並使用它。

或者,當在 Quasar CLI 專案中時,為了您的方便(因此「不是」必需的),您可以建立一個啟動檔案並提供一個 event bus(請確保您在 quasar.config 檔案 > boot 中註冊它)

一個 Quasar CLI 啟動檔案(假設是 /src/boot/bus.js)

import { EventBus } from 'quasar'
import { boot } from 'quasar/wrappers'

export default boot(({ app }) => {
  const bus = new EventBus()

  // for Options API
  app.config.globalProperties.$bus = bus

  // for Composition API
  app.provide('bus', bus)
})

然後,在您的任何元件中,您可以使用

// Options API
this.$bus

// Composition API
import { inject } from 'vue'

const bus = inject('bus') // inside setup()