Skip to content

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()

警告

手动触发仅适用于 Vue 3

¥Manual triggering only works for Vue 3

类型声明

typescript
export interface ComputedWithControlRefExtra {
  /**
   * Force update the computed value.
   */
  trigger: () => void
}
export interface ComputedRefWithControl<T>
  extends ComputedRef<T>,
    ComputedWithControlRefExtra {}
export interface WritableComputedRefWithControl<T>
  extends WritableComputedRef<T>,
    ComputedWithControlRefExtra {}
export declare function computedWithControl<T, S>(
  source: WatchSource<S> | WatchSource<S>[],
  fn: ComputedGetter<T>,
): ComputedRefWithControl<T>
export declare function computedWithControl<T, S>(
  source: WatchSource<S> | WatchSource<S>[],
  fn: WritableComputedOptions<T>,
): WritableComputedRefWithControl<T>
export { computedWithControl as controlledComputed }

源代码

源代码文档

变更日志

No recent changes

VueUse 中文网 - 粤ICP备13048890号