Published on

event hooks with mitt

Sometimes, you need to call functions from one component in another. A common solution is to use defineExpose, and some libraries, like PrimeVue, rely on it. But is there a better way?

For example, you can use useEventBus from the VueUse library or try the mitt library with a simple wrapper.

ts
import { getCurrentScope, onScopeDispose } from 'vue'
import mitt, { type EventType, Handler } from 'mitt'

const emitter = mitt()

export function useBus(name: EventType = Symbol()) {

  const onResult = (fn: Handler<unknown>) => {
    emitter.on(name, fn);
    const offFn = () => emitter.off(name, fn)
    if (getCurrentScope()) {
        onScopeDispose(offFn);
    }
    return {
        off: offFn,
    };
  };

  const call = (n: EventType, e: unknown) => emitter.emit(n, e)
  
  return { name, call, onResult }
}

example