computedEager
Eager computed without lazy evaluation.
提示
注意💡:如果您使用 Vue 3.4+,您可以直接使用 computed
。在 Vue 3.4+ 中,如果 computed 的新值沒有改變,computed
、effect
、watch
、watchEffect
、render
依賴項將不會被觸發。請參閱:https://github.com/vuejs/core/pull/5912
在 Vue:何時 computed property 可能會是錯誤的工具 了解更多資訊。
- 當您有複雜的計算正在進行,且實際上可以從快取和延遲求值中獲益,並且只有在真正必要時才應該(重新)計算時,請使用
computed()
。 - 當您有一個簡單的操作,且回傳值很少更改時(通常是布林值),請使用
computedEager()
。
示範
用法
js
import { computedEager } from '@vueuse/core'
const todos = ref([])
const hasOpenTodos = computedEager(() => !!todos.length)
console.log(hasOpenTodos.value) // false
toTodos.value.push({ title: 'Learn Vue' })
console.log(hasOpenTodos.value) // true
類型宣告
typescript
/**
* Note: If you are using Vue 3.4+, you can straight use computed instead.
* Because in Vue 3.4+, if computed new value does not change,
* computed, effect, watch, watchEffect, render dependencies will not be triggered.
* refer: https://github.com/vuejs/core/pull/5912
*
* @param fn effect function
* @param options WatchOptionsBase
* @returns readonly shallowRef
*/
export declare function computedEager<T>(
fn: () => T,
options?: WatchOptionsBase,
): Readonly<ShallowRef<T>>
export { computedEager as eagerComputed }