Files
stack/packages/mosaic/framework/skills/vueuse-functions/references/useEventBus.md
T
fargo 1a822493ba format: apply repo prettier (3.8.1) to the folded skills tree
963 markdown files reformatted with the repository's pinned prettier so
pnpm format:check covers the folded tree like every other repo file.

The formatter's embedded-language pass also normalized code fences
(TS semicolons, closed HTML tags in examples, lowercased CSS hex colors,
one renumbered list that skipped an index). Alphanumeric token deltas vs
the fold commit were audited file-by-file; all are formatter-equivalent
markup normalizations plus the four sanitized skills.
2026-08-19 14:37:17 -05:00

2.3 KiB

category
category
Utilities

useEventBus

A basic event bus.

Usage

import { useEventBus } from '@vueuse/core';

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

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

// listen to an event
const unsubscribe = bus.on(listener);

// fire an event
bus.emit('The Tokyo Olympics has begun');

// unregister the listener
unsubscribe();
// or
bus.off(listener);

// clearing all listeners
bus.reset();

Listeners registered inside of components setup will be unregistered automatically when the component gets unmounted.

TypeScript

Using EventBusKey is the key to bind the event type to the key, similar to Vue's InjectionKey util.

// 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` will be `{ name: foo }`
});

Type Declarations

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> {
  /**
   * Subscribe to an event. When calling emit, the listeners will execute.
   * @param listener watch listener.
   * @returns a stop function to remove the current callback.
   */
  on: (listener: EventBusListener<T, P>) => Fn;
  /**
   * Similar to `on`, but only fires once
   * @param listener watch listener.
   * @returns a stop function to remove the current callback.
   */
  once: (listener: EventBusListener<T, P>) => Fn;
  /**
   * Emit an event, the corresponding event listeners will execute.
   * @param event data sent.
   */
  emit: (event?: T, payload?: P) => void;
  /**
   * Remove the corresponding listener.
   * @param listener watch listener.
   */
  off: (listener: EventBusListener<T>) => void;
  /**
   * Clear all events
   */
  reset: () => void;
}
export declare function useEventBus<T = unknown, P = any>(
  key: EventBusIdentifier<T>,
): UseEventBusReturn<T, P>;