Computed and Watch
This section uses single-file component syntax for code examples
Computed values
Sometimes we need state that depends on other state - in Vue this is handled with component computed properties. To directly create a computed value, we can use the computed
method: it takes a getter function and returns an immutable reactive ref object for the returned value from the getter.
const count = ref(1)
const plusOne = computed(() => count.value++)
console.log(plusOne.value) // 2
plusOne.value++ // error
Alternatively, it can take an object with get
and set
functions to create a writable ref object.
const count = ref(1)
const plusOne = computed({
get: () => count.value + 1,
set: val => {
count.value = val - 1
}
})
plusOne.value = 1
console.log(count.value) // 0
watchEffect
To apply and automatically re-apply a side effect based on reactive state, we can use the watchEffect
method. It runs a function immediately while reactively tracking its dependencies and re-runs it whenever the dependencies are changed.
const count = ref(0)
watchEffect(() => console.log(count.value))
// -> logs 0
setTimeout(() => {
count.value++
// -> logs 1
}, 100)
Stopping the Watcher
When watchEffect
is called during a component’s setup() function or lifecycle hooks, the watcher is linked to the component’s lifecycle and will be automatically stopped when the component is unmounted.
In other cases, it returns a stop handle which can be called to explicitly stop the watcher:
const stop = watchEffect(() => {
/* ... */
})
// later
stop()
Side Effect Invalidation
Sometimes the watched effect function will perform asynchronous side effects that need to be cleaned up when it is invalidated (i.e state changed before the effects can be completed). The effect function receives an onInvalidate
function that can be used to register an invalidation callback. This invalidation callback is called when:
- the effect is about to re-run
- the watcher is stopped (i.e. when the component is unmounted if
watchEffect
is used insidesetup()
or lifecycle hooks)
watchEffect(onInvalidate => {
const token = performAsyncOperation(id.value)
onInvalidate(() => {
// id has changed or watcher is stopped.
// invalidate previously pending async operation
token.cancel()
})
})
We are registering the invalidation callback via a passed-in function instead of returning it from the callback because the return value is important for async error handling. It is very common for the effect function to be an async function when performing data fetching:
const data = ref(null)
watchEffect(async onInvalidate => {
onInvalidate(() => {...}) // we register cleanup function before Promise resolves
data.value = await fetchData(props.id)
})
An async function implicitly returns a Promise, but the cleanup function needs to be registered immediately before the Promise resolves. In addition, Vue relies on the returned Promise to automatically handle potential errors in the Promise chain.
Effect Flush Timing
Vue’s reactivity system buffers invalidated effects and flushes them asynchronously to avoid unnecessary duplicate invocation when there are many state mutations happening in the same “tick”. Internally, a component’s update
function is also a watched effect. When a user effect is queued, it is always invoked after all component update
effects:
<template>
<div>{{ count }}</div>
</template>
<script>
export default {
setup() {
const count = ref(0)
watchEffect(() => {
console.log(count.value)
})
return {
count
}
}
}
</script>
In this example:
- The count will be logged synchronously on initial run.
- When
count
is mutated, the callback will be called after the component has updated.
Note the first run is executed before the component is mounted. So if you wish to access the DOM (or template refs) in a watched effect, do it in the mounted hook:
onMounted(() => {
watchEffect(() => {
// access the DOM or template refs
})
})
In cases where a watcher effect needs to be re-run synchronously or before component updates, we can pass an additional options
object with the flush
option (default is 'post'
):
// fire synchronously
watchEffect(
() => {
/* ... */
},
{
flush: 'sync'
}
)
// fire before component updates
watchEffect(
() => {
/* ... */
},
{
flush: 'pre'
}
)
Watcher Debugging
The onTrack
and onTrigger
options can be used to debug a watcher’s behavior.
onTrack
will be called when a reactive property or ref is tracked as a dependencyonTrigger
will be called when the watcher callback is triggered by the mutation of a dependency
Both callbacks will receive a debugger event which contains information on the dependency in question. It is recommended to place a debugger
statement in these callbacks to interactively inspect the dependency:
watchEffect(
() => {
/* side effect */
},
{
onTrigger(e) {
debugger
}
}
)
onTrack
and onTrigger
only work in development mode.
watch
The watch
API is the exact equivalent of the component watch property. watch
requires watching a specific data source and applies side effects in a separate callback function. It also is lazy by default - i.e. the callback is only called when the watched source has changed.
Compared to watchEffect,
watch
allows us to:- Perform the side effect lazily;
- Be more specific about what state should trigger the watcher to re-run;
- Access both the previous and current value of the watched state.
Watching a Single Source
A watcher data source can either be a getter function that returns a value, or directly a ref
:
// watching a getter
const state = reactive({ count: 0 })
watch(
() => state.count,
(count, prevCount) => {
/* ... */
}
)
// directly watching a ref
const count = ref(0)
watch(count, (count, prevCount) => {
/* ... */
})
Watching Multiple Sources
A watcher can also watch multiple sources at the same time using an array:
watch([fooRef, barRef], ([foo, bar], [prevFoo, prevBar]) => {
/* ... */
})
Shared Behavior with watchEffect
watch
shares behavior with watchEffect
in terms of manual stoppage, side effect invalidation (with onInvalidate
passed to the callback as the 3rd argument instead), flush timing and debugging.