Skip to content

Commit cff1865

Browse files
committed
docs: update study log
1 parent 862263e commit cff1865

2 files changed

Lines changed: 56 additions & 0 deletions

File tree

English/Vue/Essentials/Watchers.md

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -216,3 +216,56 @@ precise [/prɪˈsaɪs/] 精确的;准确的;明确的\
216216
phase [/feɪz/] 阶段;时期;相位\
217217
typically [/ˈtɪpɪkli/] 典型地;通常;一般来说\
218218
terser [/ˈtɜːrsər/] 简洁的;简练
219+
220+
## Side Effect Cleanup​
221+
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:
234+
235+
```js
236+
import { watch, onWatcherCleanup } from 'vue'
237+
238+
watch(id, (newId) => {
239+
const controller = new AbortController()
240+
241+
fetch(`/api/${newId}`, { signal: controller.signal }).then(() => {
242+
// callback logic
243+
})
244+
245+
onWatcherCleanup(() => {
246+
// abort stale request
247+
controller.abort()
248+
})
249+
})
250+
```
251+
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`.

README.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,9 @@
44

55
# 日志
66

7+
## 2026.4.24
8+
[Vue doc Watchers](./English/Vue/Essentials/Watchers.md)
9+
710
## 2026.4.23
811
[Vue doc Watchers](./English/Vue/Essentials/Watchers.md)
912

0 commit comments

Comments
 (0)