Categories
Vue Answers

How to Listening to Props Changes with Vue.js?

Spread the love

Sometimes, we want to listen to changes in prop values in Vue.js components.

In this article, we’ll look at how to listen to changes in prop values in Vue.js components.

Listening to Props Changes

We can listen to props changes by using the watchers.

To add a watcher for a prop, we can add a method to the watch property.

For instance, we can write:

{
  ...
  props: ['myProp'],
  watch: {
    myProp(newVal, oldVal) {
      console.log(newVal, oldVal)
    }
  }
  ...
}

We have the watch property and the myProp prop as indicated by the props property’s value.

We just make a method with the same name as the prop with a signature that takes the new and old values respectively.

Then we get the newVal value to get the new value, and the oldVal value to get the old value.

To start watching immediately when the prop value is set, we can add the immediate property and set it to true .

For example, we can write:

watch: {
  myProp: {
    immediate: true,
    handler (val, oldVal) {
      // ...
    }
  }
}

Conclusion

We can listen to props changes by using the watchers.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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