skip to Main Content

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


  1. 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 and watchEffect are used mainly for side-effects (mutations of any variables/data).

    <script setup>
    import { ref, watch, reactive} from 'vue'
    
    const msg = ref('Hello World!')
    
    const loading = ref(false);
    const log = reactive([]);
    
    setTimeout(()=>loading.value = true);
    
    watch(loading, (val, old) => {
        
        if(old === undefined){
            // immediate
            log.push('immediate');
            return;
        }
    
        // not immediate
        log.push('not immediate');
    
    
    }, {immediate:true});
    
    </script>
    
    <template>
      <h1>{{ msg }}</h1>
      <input v-model="msg">
      <div v-for="line in log">{{line}}</div>
    </template>
    
    Login or Signup to reply.
  2. 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.

    watch(loading, (new_val, old_val) => {
        // Your code
    }, {flush:sync});
    

    By setting flush to sync, 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search