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.

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 *