Run watchers when a Vue.js component is created

Alex Jover Morales

Alex Jover Morales

Mar 31, 2019
2 min read
Share on Twitter or LinkedIn

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!

Don't miss out anything about Vue, your favourite framework.

Subscribe to receive all the articles we publish in a concise format, perfect for busy devs.

Related Articles

When to use a Vue Render Function

When should I use a render function in Vue.js? We’re going to cover some advanced Vue.js patterns when you need to use render functions.

Paul Melero

Paul Melero

Jan 27, 2022

Introduction to Render Functions

What is a render function? Let's see a simple example and the comparison with Vue compiled code and its counterpart template compiled code.

Paul Melero

Paul Melero

Sep 28, 2021

The new Provide and Inject in Vue 3

Getting stuck into the prop drilling? Learn how provide/inject can make your components more flexible and independent in this short tutorial.

Anthony Konstantinidis

Anthony Konstantinidis

Jul 18, 2022

Sponsors

VueDose is proudly supported by its sponsors. If you enjoy it, consider supporting it to ensure the project maintainability.

Silver
Learning Partner