Skip to content

computedWithControl

Category
Export Size
250 B
Last Changed
last year
Alias
controlledComputed
Related

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

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

WARNING

Manual triggering only works for Vue 3

Type Declarations

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

SourceDocs

Contributors

Anthony Fu
sun0day
kongmoumou

Changelog

v10.8.0 on 2/20/2024
a086e - fix: stricter types
v10.0.0-beta.5 on 4/13/2023
cb644 - refactor!: remove isFunction and isString utils

Released under the MIT License.

Build smarter with AI
Become an AIDD Insider
Secure early access + the best pricing & perks we'll ever offer. 24H only
Get notified
02
days
:
04
hours
:
59
minutes
:
21
seconds
: