javascript / expert
Snippet
Synchronous Watchers for Immediate State Sync
By default, Vue watchers are buffered and run asynchronously to optimize performance. Setting 'flush: sync' forces the watcher to run immediately when the dependency changes, which is critical for logic that needs to be finalized before the next DOM update cycle or for non-DOM side effects.
snippet.js
1
2
3
4
watch(source, (val) => {// Logic that must run before DOM updatesprocessedData.value = val * 2;}, { flush: 'sync' });
vue
Breakdown
1
watch(source, (val) => {
Defines a watcher observing the 'source' reactive reference.
2
processedData.value = val * 2;
Updates a dependent reactive value immediately upon change.
3
}, { flush: 'sync' });
The 'flush: sync' option bypasses the internal scheduler for instantaneous execution.