Vue js Watchers


Vue Watchers – Reactive Observers

In Vue applications, a watcher serves as a responsive listener assigned to a particular piece of internal data. Its job is to respond automatically whenever the monitored state changes—no manual calls necessary.


What Triggers a Watcher?

A watcher is passively bound to a named variable inside your data() section. Once the associated variable shifts—whether due to user action or program logic—the corresponding function inside the watch section is triggered in real-time.


Architectural Role in Vue Instance

Watchers form the fourth key part of the Vue component definition, alongside data, methods, and computed. All these segments are part of the Vue component’s internal blueprint, and watchers reside in the segment labeled watch.


Functional Blueprint

Here's the fundamental outline of where watchers reside in a Vue instance:

<!DOCTYPE html>
<html>
<head>
  <title>Vue Watcher Example</title>
</head>
<body>

  <div id="watchApp">
  <p>Quantity: {{ quantity }}</p>
    <button @click="quantity++">Add One</button>
  </div>

  <script src="https://unpkg.com/vue@3"></script>
  <script>
    const app = Vue.createApp({
      data() {
        return {
          quantity: 0
        };
      },
      watch: {
        quantity(newAmount, oldAmount) {
          console.log(`Changed from ${oldAmount} to ${newAmount}`);
        }
      }
    });

    app.mount('#watchApp');
  </script>

</body>
</html>

This logic prints a message each time quantity updates.


Dynamic Validation Illustration

Say you’re creating a rating system, and any number under 3 should show a warning. Here’s how a watcher manages this behavior automatically:

<input type="number" v-model="stars">
               <input type="number" v-model="stars"><p>{{ message }}</p> 
<!DOCTYPE html>
<html>
<head>
  <title>Vue Star Rating Watcher</title>
</head>
<body>

  <div id="ratingApp">
  <p>Stars: {{ stars }}</p>
    <p>{{ message }}</p>
    <button @click="stars--">Reduce Star</button>
    <button @click="stars++">Add Star</button>
  </div>

  <script src="https://unpkg.com/vue@3"></script>
  <script>
    const ratingApp = Vue.createApp({
      data() {
        return {
          stars: 5,
          message: ''
        };
      },
      watch: {
        stars(newScore) {
          this.message = newScore < 3 ? 'Too low!' : 'Thank you!';
        }
      }
    });

    ratingApp.mount('#ratingApp');
  </script>

</body>
</html>

Access to Previous & Current Values

Watch functions receive two arguments: the updated value and the prior one. This allows comparative logic, such as identifying trends or validating transitions.

third

Example: Cursor Tracking

Suppose you want to determine how far the cursor moved horizontally each time it's clicked. Use one variable to track X-position and another to store the movement distance:

<div @click="setX"></div> 
               <div @click="setX"></div><p>{{ moved }}</p>
watch: {   
    stars(current, previous) {     
      if (current > previous) {       
          this.message = 'Improved!';     
      } else {       
         this.message = 'Dropped!';     
     }   
  } 
}

Form Monitoring Use-Case

Consider email input verification. Rather than relying on computed values, a watcher can give feedback in real-time as the person types:

<input v-model="email"> 
               <input v-model="email"><p :class="noticeStyle">{{ notice }}</p>

Contrasts: Watcher vs. Method

Feature Watcher Method
Trigger Mechanism Automatic on data mutation Called manually (e.g., via click)
Inputs Receives new & previous values Can accept arguments or event objects
Purpose Reaction to changes Execution of logic upon action

Contrasts: Watcher vs. Computed

Feature Watcher Computed
Invocation Not used in template Can be placed directly in template
Number of dependencies One (usually) Multiple variables possible
Usage type Handles side-effects or logic branches Generates a value like a property

Watchers are ideal for running side logic—like validation, animations, or triggering HTTP requests—whenever a variable updates.


Prefer Learning by Watching?

Watch these YouTube tutorials to understand VUE JS Tutorial visually:

What You'll Learn:
  • 📌 Vue JS 3 Tutorial - 27 - Watchers
  • 📌 Vue Tutorial 9 - Watchers
Previous Next