You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Sometimes we may perform side effects, e.g. asynchronous requests, in a watcher:
222
+
223
+
```js
224
+
watch(id, (newId) => {
225
+
fetch(`/api/${newId}`).then(() => {
226
+
// callback logic
227
+
})
228
+
})
229
+
```
230
+
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.\
231
+
ideally [/aɪˈdiːəli/] 理想地;完美地;理想情况下
232
+
233
+
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:
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.
252
+
253
+
Alternatively, an `onCleanup` function is also passed to watcher callbacks as the 3rd argument, and to the `watchEffect` effect function as the first argument:\
254
+
alternatively [/ɔːlˈtɜːrnətɪvli/] 另外;或者;二者择一地
255
+
256
+
```js
257
+
watch(id, (newId, oldId, onCleanup) => {
258
+
// ...
259
+
onCleanup(() => {
260
+
// cleanup logic
261
+
})
262
+
})
263
+
264
+
watchEffect((onCleanup) => {
265
+
// ...
266
+
onCleanup(() => {
267
+
// cleanup logic
268
+
})
269
+
})
270
+
```
271
+
`onCleanup` passed via function argument is bound to the watcher instance so it is not subject to the synchronous constraint of `onWatcherCleanup`.
0 commit comments