Categories
Vue Answers

How to listen for ‘props’ changes with Vue.js?

Spread the love

In Vue.js, we can listen for changes to props using a watcher or a computed property.

Here’s how we can do it:

Using a Watcher:

<template>
  <div>
    <p>Prop value: {{ myProp }}</p>
  </div>
</template>

<script>
export default {
  props: {
    myProp: {
      type: String,
      required: true
    }
  },
  watch: {
    myProp(newValue, oldValue) {
      // Handle prop changes
      console.log('Prop value changed:', newValue);
    }
  }
};
</script>

In this example we define a watcher for the myProp prop.

Whenever the value of myProp changes, the watcher function will be invoked, and we can handle the changes inside this function.

Using a Computed Property:

<template>
  <div>
    <p>Prop value: {{ myProp }}</p>
  </div>
</template>

<script>
export default {
  props: {
    myProp: {
      type: String,
      required: true
    }
  },
  computed: {
    // Define a computed property that returns the value of the prop
    // This computed property will be re-evaluated whenever the prop changes
    myPropValue() {
      return this.myProp;
    }
  },
  watch: {
    // We can also watch the computed property if we want
    myPropValue(newValue, oldValue) {
      console.log('Prop value changed:', newValue);
    }
  }
};
</script>

In this example we define a computed property called myPropValue that simply returns the value of the myProp prop.

Whenever the value of myProp changes, the computed property will be re-evaluated, and we can watch this computed property for changes using a watcher.

Both methods achieve the same result of listening for changes to props in Vue.js. We can choose the one that fits our use case better.

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 *