Watchers·续
In particular, notice how the watcher uses todoId twice, once as the source and then again inside the callback.
This can be simplified with watchEffect(). watchEffect() allows us to track the callback's reactive dependencies automatically. The watcher above can be rewritten as:
watchEffect(async () => {
const response = await fetch(
`https://jsonplaceholder.typicode.com/todos/${todoId.value}`
)
data.value = await response.json()
})
Here, the callback will run immediately, there's no need to specify immediate: true. During its execution, it will automatically track todoId.value as a dependency (similar to computed properties). Whenever todoId.value changes, the callback will be run again. With watchEffect(), we no longer need to pass todoId explicitly as the source value.
You can check out this example of watchEffect() and reactive data-fetching in action.
For examples like these, with only one dependency, the benefit of watchEffect() is relatively small. But for watchers that have multiple dependencies, using watchEffect() removes the burden of having to maintain the list of dependencies manually. In addition, if you need to watch several properties in a nested data structure, watchEffect() may prove more efficient than a deep watcher, as it will only track the properties that are used in the callback, rather than recursively tracking all of them.
[!TIP]
watchEffectonly tracks dependencies during its synchronous execution. When using it with an async callback, only properties accessed before the firstawaittick will be tracked.
watch vs. watchEffect
watch and watchEffect both allow us to reactively perform side effects. Their main difference is the way they track their reactive dependencies:
-
watchonly tracks the explicitly watched source. It won't track anything accessed inside the callback. In addition, the callback only triggers when the source has actually changed.watchseparates dependency tracking from the side effect, giving us more precise control over when the callback should fire. -
watchEffect, on the other hand, combines dependency tracking and side effect into one phase. It automatically tracks every reactive property accessed during its synchronous execution. This is more convenient and typically results in terser code, but makes its reactive dependencies less explicit.
Side Effect Cleanup
Sometimes we may perform side effects, e.g. asynchronous requests, in a watcher:
watch(id, (newId) => {
fetch(`/api/${newId}`).then(() => {
// callback logic
})
})
export default {
watch: {
id(newId) {
fetch(`/api/${newId}`).then(() => {
// callback logic
})
}
}
}
But what if id changes before the request completes? When the previous request completes, it will still fire the callback with an ID value that is already stale. Ideally, we want to be able to cancel the stale request when id changes to a new value.
We can use the onWatcherCleanup() API to register a cleanup function that will be called when the watcher is invalidated and is about to re-run:
```js {10-13} import { watch, onWatcherCleanup } from 'vue'
watch(id, (newId) => { const controller = new AbortController()
fetch(/api/${newId}, { signal: controller.signal }).then(() => {
// callback logic
})
onWatcherCleanup(() => { // abort stale request controller.abort() }) })
```js {12-15}
import { onWatcherCleanup } from 'vue'
export default {
watch: {
id(newId) {
const controller = new AbortController()
fetch(`/api/${newId}`, { signal: controller.signal }).then(() => {
// callback logic
})
onWatcherCleanup(() => {
// abort stale request
controller.abort()
})
}
}
}
Note that onWatcherCleanup is only supported in Vue 3.5+ and must be called during the synchronous execution of a watchEffect effect function or watch callback function: you cannot call it after an await statement in an async function.
Alternatively, an onCleanup function is also passed to watcher callbacks as the 3rd argument, and to the watchEffect effect function as the first argument:
watch(id, (newId, oldId, onCleanup) => {
// ...
onCleanup(() => {
// cleanup logic
})
})
watchEffect((onCleanup) => {
// ...
onCleanup(() => {
// cleanup logic
})
})
export default {
watch: {
id(newId, oldId, onCleanup) {
// ...
onCleanup(() => {
// cleanup logic
})
}
}
}
onCleanup passed via function argument is bound to the watcher instance so it is not subject to the synchronous constraint of onWatcherCleanup.
Callback Flush Timing
When you mutate reactive state, it may trigger both Vue component updates and watcher callbacks created by you.
Similar to component updates, user-created watcher callbacks are batched to avoid duplicate invocations. For example, we probably don't want a watcher to fire a thousand times if we synchronously push a thousand items into an array being watched.
By default, a watcher's callback is called after parent component updates (if any), and before the owner component's DOM updates. This means if you attempt to access the owner component's own DOM inside a watcher callback, the DOM will be in a pre-update state.
Post Watchers
If you want to access the owner component's DOM in a watcher callback after Vue has updated it, you need to specify the flush: 'post' option:
```js{6} export default { // ... watch: { key: { handler() {}, flush: 'post' } } }
```js{2,6}
watch(source, callback, {
flush: 'post'
})
watchEffect(callback, {
flush: 'post'
})
Post-flush watchEffect() also has a convenience alias, watchPostEffect():
import { watchPostEffect } from 'vue'
watchPostEffect(() => {
/* executed after Vue updates */
})
Sync Watchers
It's also possible to create a watcher that fires synchronously, before any Vue-managed updates:
```js{6} export default { // ... watch: { key: { handler() {}, flush: 'sync' } } }
```js{2,6}
watch(source, callback, {
flush: 'sync'
})
watchEffect(callback, {
flush: 'sync'
})
Sync watchEffect() also has a convenience alias, watchSyncEffect():
import { watchSyncEffect } from 'vue'
watchSyncEffect(() => {
/* executed synchronously upon reactive data change */
})
[!WARNING] Use with Caution Sync watchers do not have batching and triggers every time a reactive mutation is detected. It's ok to use them to watch simple boolean values, but avoid using them on data sources that might be synchronously mutated many times, e.g. arrays.
this.$watch() *
It's also possible to imperatively create watchers using the $watch() instance method:
export default {
created() {
this.$watch('question', (newQuestion) => {
// ...
})
}
}
This is useful when you need to conditionally set up a watcher, or only watch something in response to user interaction. It also allows you to stop the watcher early.
Stopping a Watcher
Watchers declared using the watch option or the $watch() instance method are automatically stopped when the owner component is unmounted, so in most cases you don't need to worry about stopping the watcher yourself.
In the rare case where you need to stop a watcher before the owner component unmounts, the $watch() API returns a function for that:
const unwatch = this.$watch('foo', callback)
// ...when the watcher is no longer needed:
unwatch()
Watchers declared synchronously inside setup() or <script setup> are bound to the owner component instance, and will be automatically stopped when the owner component is unmounted. In most cases, you don't need to worry about stopping the watcher yourself.
The key here is that the watcher must be created synchronously: if the watcher is created in an async callback, it won't be bound to the owner component and must be stopped manually to avoid memory leaks. Here's an example:
<script setup>
import { watchEffect } from 'vue'
// this one will be automatically stopped
watchEffect(() => {})
// ...this one will not!
setTimeout(() => {
watchEffect(() => {})
}, 100)
</script>
To manually stop a watcher, use the returned handle function. This works for both watch and watchEffect:
const unwatch = watchEffect(() => {})
// ...later, when no longer needed
unwatch()
Note that there should be very few cases where you need to create watchers asynchronously, and synchronous creation should be preferred whenever possible. If you need to wait for some async data, you can make your watch logic conditional instead:
// data to be loaded asynchronously
const data = ref(null)
watchEffect(() => {
if (data.value) {
// do something when data is loaded
}
})
