javascript / intermediate
Snippet
Fine-tuning Watchers with Flush Timing
By default, Vue watchers run before DOM updates. Using flush: 'post' ensures the watcher callback executes after the DOM has been updated, which is crucial when you need to access the updated DOM elements.
snippet.js
1
2
3
4
5
6
7
8
import { ref, watch } from 'vue';const count = ref(0);const elementRef = ref(null);watch(count, (newVal) => {// By default, elementRef.value might not reflect the updated DOM yetconsole.log('Watcher triggered');}, { flush: 'post' });
vue
Breakdown
1
flush: 'post'
Tells Vue to defer the watcher callback until after the DOM rendering cycle is complete.