In vue3, if I have something like this
watch(loading, (new_val, old_val) => {
// how can I check if this function ran from the immediate being true, or when it changed after the immediate ran?
}, {immediate:true});
Is there something like this?
watch(loading, (new_val, old_val, options) => {
console.log(options.immediate); // prints true the first time, and then false afterwords
}, {immediate:true});
Thanks
2
Answers
Vue3 SFC Playground
Initially the old value is
undefined
.You could also try
watchEffect
. It executes immediately and collects all reactive values it reads from as watch values inside the callback on the first execution. So there’s no need to give it what to watch. That’s determined automatically.But if you don’t mutate anything in the callback consider using
computed
.watch
andwatchEffect
are used mainly for side-effects (mutations of any variables/data).In Vue 3, you can determine if a watcher function ran immediately by checking the flush option of the watcher. The flush option determines when the watcher is triggered and how it behaves.
By setting
flush
tosync
, the watcher’s callback function will be executed immediately during the component’s setup, allowing you to determine if it ran immediately or not.Note : Using
sync
flush option can have performance implications, as it runs the watcher immediately and synchronously. It is recommended to use it sparingly and only when necessary.