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

Setting up a full static Nuxt site

Overwhelmed by too many options to create a blog? Chill and use Nuxt, Storyblok and TailwindCSS to make it simple, beautiful and incredibly performant

Alex Jover Morales

Alex Jover Morales

Jul 14, 2020

Use Composition API to easily handle API requests in Vue.js

Not sure how to organize your API client in Vue.js? Learn this simple technique on how to do it using the new Composition API and make it easy.

Carlos Rodrigues

Carlos Rodrigues

Jul 6, 2020

Build a Game in Vuejs with Phaser

Love video games and Vue.js? Then check this tutorial and learn how to build a game using Phaser, the javascript game engine for the web.

Quique Fdez Guerra

Quique Fdez Guerra

Jun 22, 2020

Sponsors

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

Silver
StoryBlok
Learning Partner
Vue School