Skip to content

Commit cdb7054

Browse files
committed
Document why watched template refs require theflush: 'post' option …
vuejs/docs@efbbe59#diff-0d7cf8a91f2b75133d55bf4cdc5d6d0ff19310e1c836adf7fabd0ac4cf5e87d0
1 parent 502cfde commit cdb7054

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed

src/guide/composition-api-template-refs.md

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,3 +85,66 @@ export default {
8585
}
8686
</script>
8787
```
88+
89+
## Watching Template Refs
90+
91+
Watching a template ref for changes can be an alternative to the use of lifecycle hooks that was demonstrated in the previous examples.
92+
93+
But a key difference to lifecycle hooks is that `watch()` and `watchEffect()` effects are run *before* the DOM is mounted or updated so the template ref hasn't been updated when the watcher runs the effect:
94+
95+
```vue
96+
<template>
97+
<div ref="root">This is a root element</div>
98+
</template>
99+
100+
<script>
101+
import { ref, watchEffect } from 'vue'
102+
103+
export default {
104+
setup() {
105+
const root = ref(null)
106+
107+
watchEffect(() => {
108+
// This effect runs before the DOM is updated, and consequently,
109+
// the template ref does not hold a reference to the element yet.
110+
console.log(root.value) // => null
111+
})
112+
113+
return {
114+
root
115+
}
116+
}
117+
}
118+
</script>
119+
```
120+
121+
Therefore, watchers that use template refs should be defined with the `flush: 'post'` option. This will run the effect *after* the DOM has been updated and ensure that the template ref stays in sync with the DOM and references the correct element.
122+
123+
```vue
124+
<template>
125+
<div ref="root">This is a root element</div>
126+
</template>
127+
128+
<script>
129+
import { ref, watchEffect } from 'vue'
130+
131+
export default {
132+
setup() {
133+
const root = ref(null)
134+
135+
watchEffect(() => {
136+
console.log(root.value) // => <div></div>
137+
},
138+
{
139+
flush: 'post'
140+
})
141+
142+
return {
143+
root
144+
}
145+
}
146+
}
147+
</script>
148+
```
149+
150+
* See also: [Computed and Watchers](./reactivity-computed-watchers.html#effect-flush-timing)

0 commit comments

Comments
 (0)