Skip to content

Commit

Permalink
feat(eagerComputed): new function (#720)
Browse files Browse the repository at this point in the history
Co-authored-by: LinusBorg <LinusBorg@users.noreply.github.com>
  • Loading branch information
antfu and LinusBorg committed Sep 6, 2021
1 parent 991bfa8 commit 4690509
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
25 changes: 25 additions & 0 deletions 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
```
14 changes: 14 additions & 0 deletions 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<T>(fn: () => T): Readonly<Ref<T>> {
const result = shallowRef()

watchSyncEffect(() => {
result.value = fn()
})

return readonly(result)
}

0 comments on commit 4690509

Please sign in to comment.