How to listen for props changes in VueJS?

featured Image

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?

Related Posts

featured Image

How to add common header and footer in vuejs.

Here, in this article, we will learn how to add a common header and footer component in our vuejs application. In general, we always have the same header and footer…

Read more
featured Image

How to call a function in VUE template?

Here, we will learn on how to call a function in vue template. First, we have to define the function in the methods. and then we can use an event…

Read more
featured Image

How to redirect to external url in vue

Here, we will learn how to redirect to an external URL in vuejs application. Page Navigation is one of the basic features of a website. It helps us to navigate…

Read more

Leave a Reply

Your email address will not be published. Required fields are marked *