DEV Community

Discussion on: Vue: When a computed property can be the wrong tool

Collapse
yongjun21 profile image
Yong Jun • Edited

I actually encountered similar issue but arrived at a different solution:

function useMemo<T>(reference: Ref<T>, getKey: (v: T) => unknown = v => v) {
  let memo: Ref<T>;
  return computed(() => {
    if (!memo) {
      memo = ref(reference.value) as Ref<T>;
      watch(
        () => getKey(reference.value),
        (key, prevKey) => {
          memo.value = reference.value;
        },
        { flush: 'sync' }
      );
    }
    return memo.value;
  });
}
Enter fullscreen mode Exit fullscreen mode

Wrote a useMemo function that returns a wrapped reference that triggers downstream watcher only when some memorization key from the original reference changed. Hence combining the best of computed and watch.

Need to point out that there some difference in my requirement hence eagerComputed not suitable. In my case

  1. I need the computed to stay lazy.
  2. The computed value is an object reconstructed on every compute so referential equality used in eagerComputed will fail.