跳到內容

computedWithControl

類別
匯出大小
267 B
上次變更
3 週前
別名
controlledComputed
相關

明確定義 computed 的依賴項。

用法

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 ref 會。

ts
console.log(computedRef.value) // 0

counter.value += 1

console.log(computedRef.value) // 0

source.value = 'bar'

console.log(computedRef.value) // 1

手動觸發

您也可以透過以下方式手動觸發 computed 的更新

ts
const computedRef = computedWithControl(
  () => source.value,
  () => counter.value,
)

computedRef.trigger()

警告

手動觸發僅適用於 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 }

原始碼

Source文件

貢獻者

Anthony Fu
Anthony Fu
Yun Hao
sun0day
kongmoumou

更新日誌

v12.0.0-beta.1 於 11/21/2024
0a9ed - feat!: 移除 Vue 2 支援,優化 bundle 並清理 (#4349)
v11.0.0-beta.3 於 8/14/2024
5725a - fix: 允許 computedWithControl getter 中的可選 oldValue 參數 (#4132)
v10.8.0 於 2/20/2024
a086e - fix: 更嚴格的類型
v10.0.0-beta.5 於 4/13/2023
cb644 - refactor!: 移除 isFunctionisString 工具函式

以 MIT 授權條款發布。