Loading source
Pulling the file list, source metadata, and syntax-aware rendering for this listing.
Source from repo
Apply VueUse composables in Vue 3/Nuxt projects to replace custom implementations with battle-tested utilities.
Files
Skill
Size
Entrypoint
Format
Open file
Syntax-highlighted preview of this file as included in the skill package.
references/useEventBus.md
1---2category: Utilities3---45# useEventBus67A basic event bus.89## Usage1011```ts12import { useEventBus } from '@vueuse/core'1314const bus = useEventBus<string>('news')1516function listener(event: string) {17console.log(`news: ${event}`)18}1920// listen to an event21const unsubscribe = bus.on(listener)2223// fire an event24bus.emit('The Tokyo Olympics has begun')2526// unregister the listener27unsubscribe()28// or29bus.off(listener)3031// clearing all listeners32bus.reset()33```3435Listeners registered inside of components `setup` will be unregistered automatically when the component gets unmounted.3637## TypeScript3839Using `EventBusKey` is the key to bind the event type to the key, similar to Vue's [`InjectionKey`](https://antfu.me/posts/typed-provide-and-inject-in-vue) util.4041```ts42// fooKey.ts43import type { EventBusKey } from '@vueuse/core'4445export const fooKey: EventBusKey<{ name: foo }> = Symbol('symbol-key')46```4748```ts49import { useEventBus } from '@vueuse/core'5051import { fooKey } from './fooKey'5253const bus = useEventBus(fooKey)5455bus.on((e) => {56// `e` will be `{ name: foo }`57})58```5960## Type Declarations6162```ts63export type EventBusListener<T = unknown, P = any> = (64event: T,65payload?: P,66) => void67export type EventBusEvents<T, P = any> = Set<EventBusListener<T, P>>68export interface EventBusKey<T> extends Symbol {}69export type EventBusIdentifier<T = unknown> = EventBusKey<T> | string | number70export interface UseEventBusReturn<T, P> {71/**72* Subscribe to an event. When calling emit, the listeners will execute.73* @param listener watch listener.74* @returns a stop function to remove the current callback.75*/76on: (listener: EventBusListener<T, P>) => Fn77/**78* Similar to `on`, but only fires once79* @param listener watch listener.80* @returns a stop function to remove the current callback.81*/82once: (listener: EventBusListener<T, P>) => Fn83/**84* Emit an event, the corresponding event listeners will execute.85* @param event data sent.86*/87emit: (event?: T, payload?: P) => void88/**89* Remove the corresponding listener.90* @param listener watch listener.91*/92off: (listener: EventBusListener<T>) => void93/**94* Clear all events95*/96reset: () => void97}98export declare function useEventBus<T = unknown, P = any>(99key: EventBusIdentifier<T>,100): UseEventBusReturn<T, P>101```102