Categories
JavaScript Vue

Listen for Prop Changes in a Vue Component

Spread the love

We can listen for prop changes by using the watch property.

For instance, we can write:

new Vue({
  el: '#app',
  components: {
    'child' : {
      template: `<p>{{ myProp }}</p>`,
      props: ['myProp'],
      watch: { 
      	myProp(newVal, oldVal) { 
          //...
        }
      }
    }
  }
});

We set props to ['myProp'] to indicate that we’re accepting myProp as a prop.

Then in the watch property, we have the method with the same name to get the old and new values of the prop as parameters.

newVal has the new value and oldVal has the old one.

Then we can do whatever we want with it.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.