Javascript is required
ยท
1 min read

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

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

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
1<script setup>
2watch(source, callback, {
3  flush: 'post',
4})
5
6watchEffect(callback, {
7  flush: 'post',
8})
9</script>

Example for Vue 2 with Options API:

Component.vue
1<script>
2export 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():

Component.vue
1<script setup>
2import { watchPostEffect } from 'vue'
3
4watchPostEffect(() => {
5  /* executed after Vue updates */
6})
7</script>

If you liked this Vue tip, follow me on X to get notified about new tips, blog posts, and more. Alternatively (or additionally), you can subscribe to my weekly Vue & Nuxt newsletter:

I will never share any of your personal data. You can unsubscribe at any time.