Deep Watch and Immediate Callback Execution in Vue.js

Basic Watch Usage

For a list page that requires automatic search when users input keywords, you can use watch to monitor search value changes instead of relying solely on input change events.

<template>
  <div>
    <div class="search-container">
      <label>Search</label>
      <input v-model="queryText" />
    </div>
    <!-- List content omitted -->
  </div>
</template>

<script>
export default {
  data() {
    return {
      queryText: ''
    }
  },
  watch: {
    queryText(currentVal, previousVal) {
      if (currentVal !== previousVal) {
        this.fetchResults();
      }
    }
  },
  methods: {
    fetchResults() {
      // Fetch data with debouncing
    }
  }
}
</script>

Immediate Execution

To load data during component initialization without calling the method in lifecycle hooks, configure the immediate property.

export default {
  watch: {
    queryText: {
      handler(currentVal, previousVal) {
        if (currentVal !== previousVal) {
          this.fetchResults();
        }
      },
      immediate: true
    }
  }
}

Initial execution passes an empty string as currentVal and undefined as previousVal.

Deep Watching

When monitoring form changes to track edit status, deep watchnig eliminates the need to watch each individual property.

export default {
  data() {
    return {
      userForm: {
        name: '',
        gender: '',
        age: 0,
        departmentId: ''
      }
    }
  },
  watch: {
    userForm: {
      handler(currentVal, previousVal) {
        // Update edit status
      },
      deep: true
    }
  }
}

Due to object reference equality, currentVal and previousVal remain identical.

Programmatic Watch Control

For edit forms requiring conditional watch activation after data population, use $watch for dynamic control.

export default {
  data() {
    return {
      userForm: {
        name: '',
        age: 0
      }
    }
  },
  created() {
    this.initializeData();
  },
  methods: {
    initializeData() {
      setTimeout(() => {
        this.userForm = {
          name: 'Alice',
          age: 25
        };
        
        const watcher = this.$watch(
          'userForm',
          () => {
            console.log('Form modified');
          },
          { deep: true }
        );
        
        setTimeout(() => {
          this.userForm.name = 'Bob';
        }, 1000);
      }, 1000);
    }
  }
}

Call watcher() to terminate observation when needed.

Tags: Vue.js WATCH Deep Watch Immediate Reactivity

Posted on Tue, 07 Jul 2026 17:05:37 +0000 by poelinca