Menu
×
   ❮   
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS R TYPESCRIPT ANGULAR GIT POSTGRESQL MONGODB ASP AI GO KOTLIN SASS VUE DSA GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE
     ❯   

Vue Tutorial

Vue HOME Vue Intro Vue Directives Vue v-bind Vue v-if Vue v-show Vue v-for Vue Events Vue v-on Vue Methods Vue Event Modifiers Vue Forms Vue v-model Vue CSS Binding Vue Computed Properties Vue Watchers Vue Templates

Scaling Up

Vue Why, How and Setup Vue First SFC Page Vue Components Vue Props Vue v-for Components Vue $emit() Vue Fallthrough Attributes Vue Scoped Styling Vue Local Components Vue Slots Vue v-slot Vue Scoped Slots Vue Dynamic Components Vue Teleport Vue HTTP Request Vue Template Refs Vue Lifecycle Hooks Vue Provide/Inject Vue Routing Vue Form Inputs Vue Animations Vue Animations with v-for Vue Build Vue Composition API

Vue Reference

Vue Built-in Attributes Vue Built-in Components Vue Built-in Elements Vue Component Instance Vue Directives Vue Instance Options Vue Lifecycle Hooks

Vue Examples

Vue Examples Vue Exercises Vue Quiz Vue Server Vue Certificate

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



×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
[email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
[email protected]

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.