·
1 min read
Vue Tip: Access DOM in Watcher Callback After Vue Updated It
MH
Michael Hoffmann
@mokkapps
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:
Component.vue
<script setup>
watch(source, callback, {
flush: 'post',
})
watchEffect(callback, {
flush: 'post',
})
</script>
Example for Vue 2 with Options API:
Component.vue
<script>
export default {
// ...
watch: {
key: {
handler() {},
flush: 'post',
},
},
}
</script>
Post-flush watchEffect()
also has a convenience alias, watchPostEffect()
:
Component.vue
<script setup>
import { watchPostEffect } from 'vue'
watchPostEffect(() => {
/* executed after Vue updates */
})
</script>
If you liked this Vue tip, follow me on BlueSky to get notified about new tips, blog posts, and more. Alternatively (or additionally), you can subscribe to my weekly Vue & Nuxt newsletter :