DEV Community

Cover image for Introduction to Vue Watchers
Linda
Linda

Posted on

Introduction to Vue Watchers

In this article, we will be discussing watchers, one of the core concepts in Vue.js.

Watchers, just as the name implies are used to watch out for changes in a property previously defined in the data object. It is triggered whenever the value of that property changes.

Let's create a watcher for an "answer" property below. The watcher must have the same name as the property being observed.

export default {
  data() {
    return {
      answer: ''
    }
  },
  watch: {
    answer: function() {
      console.log(this.answer)
    }
  },
}
Enter fullscreen mode Exit fullscreen mode

The Watcher above will log the "answer" property to the console anytime its value changes.

We can also access the old property value and new property value in a Watcher by adding two optional parameters as shown below.

export default {
  data() {
    return {
      answer: ''
    }
  },
  watch: {
    answer: function(oldAnswer, newAnswer) {
      console.log(`The answer has been changed from ${oldAnswer} to ${newAnswer}`)
    }
  },

}
Enter fullscreen mode Exit fullscreen mode

If we want to monitor the changes of items within an array or the properties of an object we use "deep". Let's watch out for changes in the "person" Object below.

export default {
  data() {
    return {
      person: {
          name: 'Linda',
          gender: 'Female',
          signedIn: false
      }
    }
  },
  watch: {
    person: {
      deep: true, // Vue now watches for changes within the person Object
      handler() {
        if (this.person.isSignedIn) this.records++
      }
    }
  },

}
Enter fullscreen mode Exit fullscreen mode

As a practical example, I have created a simple "App" where we use a Watcher to monitor the number of times a user has signed.

That's all folks, See you next week!

Top comments (5)

Collapse
 
kennyrafael profile image
kennyrafael • Edited

Would be nice to add immediate: true. This way you can do something like this:

selectedAuthor: {
      handler: 'fetchPosts',
      immediate: true
},
data: function () {
      selectedAuthor: 0,
      authors: [...]
}
Enter fullscreen mode Exit fullscreen mode

immediate: true means your handler will trigger when the component is mounted, and again when the property changes.

Collapse
 
lindaojo profile image
Linda

Sweet!

Collapse
 
sirnino profile image
Antonino Sirchia

Very interesting. This makes me think about remote logging of events...

Collapse
 
adeviss2 profile image
Alain Deviss

This is old vue

Collapse
 
koas profile image
Koas

Nice article! I didn’t know about the deep member.