UNPKG

@cran/lib.vue.ref

Version:

Vue Reactivity Extensions

33 lines (27 loc) 961 B
import { type ShallowRef, shallowReadonly, shallowRef, watchEffect } from "vue"; /** * @since 0.0.1 * @category Utility */ // eslint-disable-next-line @typescript-eslint/no-explicit-any export type EagerComputed<T = any> = ReturnType<typeof eagerComputed<T>>; /** * Use computed() when you have a complex * calculation going on, which can actually profit * from caching and lazy evaluation and should only * be (re-)calculated if really necessary. * * Use eagerComputed() when you have a simple * operation, with a rarely changing return value – * often a boolean. * @since 0.0.1 * @category Utility * @see https://dev.to/linusborg/vue-when-a-computed-property-can-be-the-wrong-tool-195j */ export function eagerComputed<T> ( factory: ( ) => T ) { const result = shallowRef<T>(); watchEffect(function onEffect ( ) { result.value = factory(); }, { flush: "sync", }); return shallowReadonly(result) as Readonly<ShallowRef<T>>; }