computedWithControl
算出プロパティの依存関係を明示的に定義します。
使用方法
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
手動トリガー
以下の方法で算出プロパティの更新を手動でトリガーすることもできます。
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 }
ソース
貢献者
変更履歴
v12.0.0-beta.1
2024/11/21v11.0.0-beta.3
2024/8/14v10.8.0
2024/2/20a086e
- fix: より厳密な型v10.0.0-beta.5
2023/4/13cb644
- refactor!: `isFunction` と `isString` ユーティリティを削除