computedEager
立即计算,无需惰性求值。
提示
注意💡: 如果您正在使用 Vue 3.4+,您可以直接使用 computed
。在 Vue 3.4+ 中,如果计算出的新值没有改变,computed
、effect
、watch
、watchEffect
、render
的依赖项将不会被触发。参见:https://github.com/vuejs/core/pull/5912
了解更多信息请访问 Vue: 何时计算属性可能是错误的工具。
- 当您进行复杂的计算时,可以使用
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 }