diff --git a/packages/shared/eagerComputed/index.md b/packages/shared/eagerComputed/index.md new file mode 100644 index 000000000000..fc381c0c1abf --- /dev/null +++ b/packages/shared/eagerComputed/index.md @@ -0,0 +1,25 @@ +--- +category: Utilities +--- + +# eagerComputed + +Eager computed without lazy evaluation. + +Learn more at [Vue: When a computed property can be the wrong tool](https://dev.to/linusborg/vue-when-a-computed-property-can-be-the-wrong-tool-195j). + +- 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. + +## Usage + +```js +import { eagerComputed } from '@vueuse/core' + +const todos = ref([]) +const hasOpenTodos = eagerComputed(() => !!todos.length) + +console.log(hasOpenTodos.value) // 0 +toTodos.value.push({ title: 'Learn Vue' }) +console.log(hasOpenTodos.value) // 1 +``` diff --git a/packages/shared/eagerComputed/index.ts b/packages/shared/eagerComputed/index.ts new file mode 100644 index 000000000000..48a1657278e7 --- /dev/null +++ b/packages/shared/eagerComputed/index.ts @@ -0,0 +1,14 @@ +// ported from https://dev.to/linusborg/vue-when-a-computed-property-can-be-the-wrong-tool-195j +// by @linusborg https://github.com/LinusBorg + +import { readonly, Ref, shallowRef, watchSyncEffect } from 'vue-demi' + +export function eagerComputed(fn: () => T): Readonly> { + const result = shallowRef() + + watchSyncEffect(() => { + result.value = fn() + }) + + return readonly(result) +}