Skip to content

Vue.js 2 Watchers

New Course Coming Soon:

Get Really Good at Git

A Vue watcher allows you to listen to the component data and run whenever a particular property changes

A watcher is a special Vue.js feature that allows you to spy on one property of the component state, and run a function when that property value changes.

Here’s an example. We have a component that shows a name, and allows you to change it by clicking a button:

<template>
  <p>My name is {{name}}</p>
  <button @click="changeName()">Change my name!</button>
</template>

<script>
export default {
  data() {
    return {
      name: 'Flavio'
    }
  },
  methods: {
    changeName: function() {
      this.name = 'Flavius'
    }
  }
}
</script>

When the name changes we want to do something, like printing a console log.

We can do so by adding to the watch object a property named as the data property we want to watch over:

<script>
export default {
  data() {
    return {
      name: 'Flavio'
    }
  },
  methods: {
    changeName: function() {
      this.name = 'Flavius'
    }
  },
  watch: {
    name: function() {
      console.log(this.name)
    }
  }
}
</script>

The function assigned to watch.name can optionally accept 2 parameters. The first is the new property value. The second is the old property value:

<script>
export default {
  /* ... */
  watch: {
    name: function(newValue, oldValue) {
      console.log(newValue, oldValue)
    }
  }
}
</script>

Watchers cannot be looked up from a template as you can with computed properties.

Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. A course that helps you feel less frustrated with Git. Launching Summer 2024. Join the waiting list!
→ Get my Vue.js 2 Handbook

Here is how can I help you: