How to listen for props changes in VueJS?


How to listen for props changes in VueJS?

In this article, we learn how to listen for props changes in vue.

In VueJS, props are the properties which are sent from the parent component to its child components.

Here, we will listen for any prop changes that occur in the parent component and are passed on to the child component.

To listen for any changes we will use the watcher or watch property of VueJS.

The watch property helps us to listen to component data and runs whenever the value of any particular property changes.

Listen to props change using watch in vue.

In this example, we have a parent component and a child component. And we pass the name from the parent to its child component as a prop.

And in parent.vue component, we have a Change Name button which when clicked will change the name from John to Alex and then pass the change name value to child.vue component.

Parent.vue :

<template>
  <div id="app">
    <child :name="myName" />
    <button @click="changeName()">Change Name</button>
  </div>
</template>

<script>
import Child from "./components/Child";

export default {
  name: "App",
  components: {
    Child,
  },
  data() {
    return {
      myName: "john",
    };
  },
  methods: {
    changeName() {
      this.myName = "Alex";
    },
  },
};
</script>

In child.vue component, we have received the prop name and displayed it on the template.

child.vue

<template>
  <div class="child">Name is : {{ name }}</div>
</template>

<script>
export default {
  name: "Child",
  props: {
    name: {
      type: String,
    },
  },
  watch: { // It listens to the change in prop name
    name: function () {
      console.log("name change"); // print out when the name changes
    },
  },
};
</script>

Here, we have the watch property which is listening to prop name, and when it gets changed, it logs "name changed in prop" in the console.

Here is the code:

Edit async-fog-fsus0

Related Topics:

How to set default value of props in VueJS ?

How to call a function in VUE template?