javascript / expert
Snippet
Automatic Side-Effect Disposal with onWatcherCleanup
Vue 3.5 introduced onWatcherCleanup to simplify side-effect management within watchers. Previously, cleanup was handled via a parameter in the watch callback. This new standalone function allows for cleaner logic, especially when using async/await or extracting cleanup logic into helper functions. It ensures that stale requests or event listeners are disposed of before the watcher triggers again.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
import { watch, onWatcherCleanup } from 'vue';watch(id, (newId) => {const controller = new AbortController();fetch(`/api/data/${newId}`, { signal: controller.signal }).then(res => res.json()).then(data => /* handle data */ {});// Vue 3.5+: cleanup runs before the next watch execution or component unmountonWatcherCleanup(() => {controller.abort();});});
vue
Breakdown
1
onWatcherCleanup(() => {
Registers a cleanup function specifically for the current execution of the watcher effect.
2
controller.abort();
Stops the previous fetch request to prevent race conditions when the 'id' changes rapidly.