fix them all

  • Published on

    d3

    If you need to use D3 and your code is turning into a mess, try organizing it with composable functions.

    js
    export function useD3(refName, cb = () => {}) {
      const refSelector = useTemplateRef(refName)
      watchPostEffect(() => cb(select(toValue(refSelector))))
    }

    example

  • 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