Run watchers when a Vue.js component is created

#Vue

Although Vue.js provides us with computed properties which are very useful for most of the cases, in some situations you might need to use watchers.

Watchers by default are run only when the value of the property that is watched changes, and that totally makes sense.

Here’s how you define a watcher for a dog property:

export default {
  data: () => ({
    dog: ""
  }),
  watch: {
    dog(newVal, oldVal) {
      console.log(`Dog changed: ${newVal}`);
    }
  }
};

So far so good. If you try that code, the dog watch function would be called as soon as its value changes.

However, in some situations you need the watcher to be run as soon as the component is created. You could move the logic within to a method, and then call it from both the watcher and the created hook, but there is a simpler way.

You can use the long-hand version of the watcher in order to pass the immediate: true option. That will make it run instantly on component’s creation.

export default {
  data: () => ({
    dog: ""
  }),
  watch: {
    dog: {
      handler(newVal, oldVal) {
        console.log(`Dog changed: ${newVal}`);
      },
      immediate: true
    }
  }
};

As you can see, in the long-hand way you need to set the watch callback in the handler key of the object.

Do you want to see it in action? Check it out yourself in this CodeSandbox!

Remember you can read this tip online (with copy/pasteable code), and don’t forget to share VueDose with your colleagues, so they also know about these tips as well!

See you next week.

Alex

Do you want to sponsor a VueDose tip? Send an email to info@vuedose.tips and have more info!

Start saving time and get a tip about the Vue ecosystem every week, right in your inbox.