Vue Watchers

A watcher is a method that watches a data property with the same name.

A watcher runs every time the data property value changes.

Use a watcher if a certain data property value requires an action.

The Watcher Concept

Watchers is the fourth configuration option in the Vue instance that we will learn. The first three configuration options we have already looked at are 'data', 'methods' and 'computed'.

As with 'data', 'methods' and 'computed' watchers also has a reserved name in the Vue instance: 'watch'.

Syntax

const app = Vue.createApp({
  data() {
    ...
  },
  watch: {
    ...
  },
  computed: {
    ...
  },
  methods: {
    ...
  }
})

As mentioned in the green area at the top, a watcher monitors a data property with the same name.

We never call a watcher method. It is only called automatically when the property value changes.

The new property value is always available as an input argument to the watcher method, and so is the old value.

Example

An <input type="range"> element is used to change a value 'rangeVal'. A watcher is used to prevent the user from choosing values between 20 and 60 that are considered illegal.

<input type="range" v-model="rangeVal">
<p>{{ rangeVal }}</p>
const app = Vue.createApp({
  data() {
    rangeVal: 70
  },
  watch: {
    rangeVal(val){
      if( val>20 && val<60) {
        if(val<40){
          this.rangeVal = 20;
        }
        else {
          this.rangeVal = 60;
        }
      }
    }
  }
})
Try it Yourself »

A Watcher with New and Old Values

In addition to the new property value, the previous property value is also automatically available as an input argument to watcher methods.

Example

We set up click event on a <div> element to record mouse pointer x-position 'xPos' with a method 'updatePos'. A watcher calculates the difference in pixels between the new x-position and the previous with the use of old and new input arguments to the watcher method.

<div v-on:click="updatePos"></div>
<p>{{ xDiff }}</p>
const app = Vue.createApp({
  data() {
    xPos: 0,
    xDiff: 0
  },
  watch: {
    xPos(newVal,oldVal){
      this.xDiff = newVal-oldVal
    }
  },
  methods: {
    updatePos(evt) {
      this.xPos = evt.offsetX
    }
  }
})
Try it Yourself »

We can also use new and old values to give feedback to the user the exact moment the input goes from being invalid to valid:

Example

The value from an <input> element is connected to a watcher. If the value includes a '@' it is considered a valid e-mail address. The user gets a feedback text to inform if the input is valid, invalid, or if it just got valid with the last keystroke.

<input v-type="email" v-model="inpAddress">
<p v-bind:class="myClass">{{ feedbackText }}</p>
const app = Vue.createApp({
  data() {
    inpAddress: '',
    feedbackText: '',
    myClass: 'invalid'
  },
  watch: {
    inpAddress(newVal,oldVal) {
      if( !newVal.includes('@') ) {
        this.feedbackText = 'The e-mail address is NOT valid';
        this.myClass = 'invalid';
      }
      else if( !oldVal.includes('@') && newVal.includes('@') ) {
        this.feedbackText = 'Perfect! You fixed it!';
        this.myClass = 'valid';
      }
      else {
        this.feedbackText = 'The e-mail address is valid :)';
      }
    }
  }
})
Try it Yourself »

Watchers vs. Methods

Watchers and methods are both written as functions, but there are many differences:

  • Methods are called from HTML.
  • Methods are often called when an event happens.
  • Methods automatically receives the event object as an input.
  • We can also send other values we choose as an input to a method.
  • Watchers are only called when the watched data property value changes, and this happens automatically.
  • Watchers automatically receives the new and old value from the watched property.
  • We cannot choose to send any other values with a watcher as an input.

Watchers vs. Computed Properties

Watchers and computed properties are both written as functions.

Watchers and computed properties are both called automatically when a dependency change, and never called from HTML.

Here are some differences between computed properties and watchers:

  • Watchers only depend on one property, the property they are set up to watch.
  • Computed properties can depend on many properties.
  • Computed properties are used like data properties, except they are dynamic.
  • Watchers are not referred to from HTML.

Vue Exercises

Test Yourself With Exercises

Exercise:

The watcher in this exercise is supposed to increment the 'count' data property by one every time 'rangeVal' data property changes.

What must the watcher be called?

<script>
  const app = Vue.createApp({
    data() {
      return {
      	rangeVal: 70,
        count: 0
      }
    },
    watch: {
      () {
        this.count++
      }
    }
  })
 app.mount('#app')
</script>

Start the Exercise



Copyright 1999-2023 by Refsnes Data. All Rights Reserved.