Skip to content
Merged
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 44 additions & 11 deletions src/guide/reactivity-computed-watchers.md
Original file line number Diff line number Diff line change
Expand Up @@ -83,8 +83,10 @@ We are registering the invalidation callback via a passed-in function instead of

```js
const data = ref(null)
watchEffect(async (onInvalidate) => {
onInvalidate(() => { /* ... */ }) // we register cleanup function before Promise resolves
watchEffect(async onInvalidate => {
onInvalidate(() => {
/* ... */
}) // we register cleanup function before Promise resolves
data.value = await fetchData(props.id)
})
```
Expand All @@ -101,19 +103,19 @@ Vue's reactivity system buffers invalidated effects and flushes them asynchronou
</template>

<script>
export default {
setup() {
const count = ref(0)
export default {
setup() {
const count = ref(0)

watchEffect(() => {
console.log(count.value)
})
watchEffect(() => {
console.log(count.value)
})

return {
count
}
return {
count
}
}
}
</script>
```

Expand Down Expand Up @@ -211,6 +213,37 @@ firstName.value = 'John' // logs: ["John", ""] ["", ""]
lastName.value = 'Smith' // logs: ["John", "Smith"] ["John", ""]
```

However, if you are changing both watched sources simultaneously in the same method, the watcher will be executed only once:

```js{9-13}
setup() {
const firstName = ref("");
const lastName = ref("");

watch([firstName, lastName], (newValues, prevValues) => {
console.log(newValues, prevValues);
});

const changeValues = () => {
firstName.value = "John";
lastName.value = "Smith";
// logs: ["John", "Smith"] ["", ""]
};

return { changeValues };
}
```

If you want watcher to be triggered after every change, make sure to add the [nextTick](/api/global-api.html#nexttick) call between changes:

```js
const changeValues = async () => {
firstName.value = 'John' // logs: ["John", ""] ["", ""]
await nextTick()
lastName.value = 'Smith' // logs: ["John", "Smith"] ["John", ""]
}
```

### Watching Reactive Objects

Using a watcher to compare values of an array or object that are reactive requires that it has a copy made of just the values.
Expand Down