主题
computedWithControl
显式定义计算的依赖。
🌐 Explicitly define the dependencies of computed.
用法
🌐 Usage
ts
import { computedWithControl } from '@vueuse/core'
const source = ref('foo')
const counter = ref(0)
const computedRef = computedWithControl(
() => source.value, // watch source, same as `watch`
() => counter.value, // computed getter, same as `computed`
)js
import { computedWithControl } from '@vueuse/core'
const source = ref('foo')
const counter = ref(0)
const computedRef = computedWithControl(
() => source.value, // watch source, same as `watch`
() => counter.value,
)这样的话,counter 的变化不会触发 computedRef 更新,但会触发 source 引用更新。
🌐 With this, the changes of counter won't trigger computedRef to update but the source ref does.
ts
console.log(computedRef.value) // 0
counter.value += 1
console.log(computedRef.value) // 0
source.value = 'bar'
console.log(computedRef.value) // 1手动触发
🌐 Manual Triggering
你还可以通过以下方式手动触发计算的更新:
🌐 You can also manually trigger the update of the computed by:
ts
const computedRef = computedWithControl(
() => source.value,
() => counter.value,
)
computedRef.trigger()深度监控
🌐 Deep Watch
与 computed 不同,computedWithControl 默认是浅层的。 你可以指定与 watch 相同的选项来控制其行为:
🌐 Unlike computed, computedWithControl is shallow by default. You can specify the same options as watch to control the behavior:
ts
const source = ref({ name: 'foo' })
const computedRef = computedWithControl(
source,
() => counter.value,
{ deep: true },
)