Skip to content

useEventBus

类别
导出体积
332 B
上次更改
2 months ago

一个基本的事件总线。

示例

新闻频道:
电视:
--- 无信号 ---

用法

ts
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('东京奥运会已经开始了')

// 注销监听器
unsubscribe()
// 或者
bus.off(listener)

// 清除所有监听器
bus.reset()
js
import { useEventBus } from '@vueuse/core'
const bus = useEventBus('news')
function listener(event) {
  console.log(`news: ${event}`)
}
// 监听事件
const unsubscribe = bus.on(listener)
// 触发事件
bus.emit('东京奥运会已经开始了')
// 注销监听器
unsubscribe()
// 或者
bus.off(listener)
// 清除所有监听器
bus.reset()

在组件的 setup 内注册的监听器会在组件卸载时自动注销。

TypeScript

使用 EventBusKey 将事件类型绑定到键上,类似于 Vue 的 InjectionKey 工具。

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

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

import { fooKey } from './fooKey'

const bus = useEventBus(fooKey)

bus.on((e) => {
  // `e` 是 `{ name: foo }`
})

类型声明

显示类型声明
typescript
export type EventBusListener<T = unknown, P = any> = (
  event: T,
  payload?: P,
) => void
export type EventBusEvents<T, P = any> = Set<EventBusListener<T, P>>
export interface EventBusKey<T> extends Symbol {}
export type EventBusIdentifier<T = unknown> = EventBusKey<T> | string | number
export interface UseEventBusReturn<T, P> {
  /**
   * 订阅事件。调用 emit 时,监听器将执行。
   * @param listener 监听器函数。
   * @returns 用于移除当前回调的停止函数。
   */
  on: (listener: EventBusListener<T, P>) => Fn
  /**
   * 类似于 `on`,但仅触发一次。
   * @param listener 监听器函数。
   * @returns 用于移除当前回调的停止函数。
   */
  once: (listener: EventBusListener<T, P>) => Fn
  /**
   * 发射事件,相应的事件监听器将执行。
   * @param event 发送的数据。
   * @param payload 附带的负载数据。
   */
  emit: (event?: T, payload?: P) => void
  /**
   * 移除相应的监听器。
   * @param listener 监听器函数。
   */
  off: (listener: EventBusListener<T>) => void
  /**
   * 清除所有事件。
   */
  reset: () => void
}
export declare function useEventBus<T = unknown, P = any>(
  key: EventBusIdentifier<T>,
): UseEventBusReturn<T, P>

源码

源码演示文档

贡献者

Anthony Fu
一纸忘忧
Anthony Fu
TuiMao233
jahnli
丶远方
Haoqun Jiang
sun0day
webfansplz
Jairo Blatt

更新日志

v10.0.0-beta.0 on 3/14/2023
dd514 - fix(useEventBus,createEventHook)!: dedupe registration of the same function (#2748)
37ec7 - fix: use ts-ignore instead of ts-expect-error for version-specifc errors (#2802)