Vue Tip: Access DOM in Watcher Callback After Vue Updated It

Michael Hoffmann
Jan 2, 2023
| 1 min read
| 189 views
Michael Hoffmann
Jan 2, 2023
1 min read
| 189 views
Script

If you make changes to reactive state in a Vue component, it can trigger both component updates and any watcher callbacks that you have created.
By default, these callbacks are executed before the component updates, so if you try to access the DOM inside a callback, it will be in its pre-update state.
To access the DOM after Vue has updated it in a watcher callback, you can use the flush: 'post'
option:
1
<script setup>
2
watch(source, callback, {
3
flush: 'post',
4
})
5
6
watchEffect(callback, {
7
flush: 'post',
8
})
9
</script>
Example for Vue 2 with Options API:
1
<script>
2
export default {
3
// ...
4
watch: {
5
key: {
6
handler() {},
7
flush: 'post',
8
},
9
},
10
}
11
</script>
Post-flush watchEffect()
also has a convenience alias, watchPostEffect()
:
1
<script setup>
2
import { watchPostEffect } from 'vue'
3
4
watchPostEffect(() => {
5
/* executed after Vue updates */
6
})
7
</script>
If you liked this Vue tip, follow me on Twitter to get notified about new tips, blog posts, and more. Alternatively (or additionally), you can subscribe to my weekly Vue newsletter:
New Vue & Nuxt tips delivered to your inbox:
Vue Tip: Pass Custom Arguments to Event Handler MethodDec 26, 2022
Vue Tip: Dynamically Change Page TitleJan 7, 2023
Show comments