useEventBus

useEventBus

基本的なイベントバス。

使用法

import { useEventBus } from '@vueuse/core'

const bus = useEventBus<string>('news')

function listener(event: string) {
  console.log(`news: ${event}`)
}

// イベントをリッスンする
const unsubscribe = bus.on(listener)

// イベントを発火する
bus.emit('The Tokyo Olympics has begun')

// リスナーを登録解除する
unsubscribe()
// または
bus.off(listener)

// すべてのリスナーをクリアする
bus.reset()

コンポーネントのsetup内で登録されたリスナーは、コンポーネントがアンマウントされると自動的に登録解除されます。

TypeScript

EventBusKeyを使用することで、イベントタイプをキーにバインドすることができます。これは、VueのInjectionKeyユーティリティに似ています。

// fooKey.ts
import type { EventBusKey } from '@vueuse/core'

export const fooKey: EventBusKey<{ name: foo }> = Symbol('symbol-key')
import { useEventBus } from '@vueuse/core'

import { fooKey } from './fooKey'

const bus = useEventBus(fooKey)

bus.on((e) => {
  // `e`は`{ name: foo }`になります
})