What is a watcher in vuejs?

When building components in Vue, we often need to respond to changes in our props.

A watcher — or watched prop — let’s us track a property on our component and run a function whenever it changes.

For example, if the prop colour changes, we can decide to log something to the console:

export default {
  name: 'ColourChange',
  props: ['colour'],
  watch: {
    colour()
      console.log('The colour has changed!');
    }
  }
}

You can put a watcher on any reactive property. This includes computed props, as well as data that is specified inside of data() on your Vue component.

They’re really useful for creating side effects — things that don’t update your application’s state immediately.

If you need to fetch data or do some other asynchronous action, watched props are really good for that. Or maybe you need to interact with an imperative browser API, such as localstorage.

Leave a comment

Your email address will not be published. Required fields are marked *