Categories
Vue Answers

How to listen for props changes with Vue.js?

Spread the love

Sometimes, we want to listen for props changes with Vue.js

In this article, we’ll look at how to listen for props changes with Vue.js.

How to listen for props changes with Vue.js?

To listen for props changes with Vue.js, we can add a watcher for the prop.

For instance, we write

<script>
export default {
  //...
  watch: {
    myProp: {
      immediate: true,
      handler(val, oldVal) {
        // ...
      },
    },
  },
  //...
};
</script>

to watch the value of the myProp prop by setting watch.myProp to an object with immediate set to true to watch the initial value of the myProp prop.

And we set handler to a function that gets the val and oldVal values to get the new and old value of the myProp prop value respectively.

Conclusion

To listen for props changes with Vue.js, we can add a watcher for the prop.

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 *