How to listen to props changes in Vuejs| watch function example

This post is an example of how to listen to prop changes of a component in Vuejs.

Vuejs Listen and watch prop changes

Props in vuejs are used to pass values from parent to child components, also called one-way binding by default.

Sometimes we want to watch props changes to know what was changed and its previous value.

Props in parent components contain initialed with an initial value, Child components use its value as a local value and make the necessary changes.

In vuejs, watch functions provide to watch changes.

Syntax of watch function:

export default { name: "ChildComponent", props: ["name"], watch: { name:
function (newValue, oldValue) { console.log("newValue: %s, previousValue: %s",
newValue, oldValue); }, }, };

Let’s declare ChildComponent.vue

In ChildComponent.vue, the parent component receives Property and displays it on the browser.

There is a watch function to listen to changes that emit old values and new values.

<template>
  <div>
    <h1>hello, {{ name }}</h1>
  </div>
</template>

<script>
export default {
  name: "MyComponent",
  props: {
    name: String,
  },
  watch: {
    name: function (newValue, oldValue) {
      console.log("newValue: %s, previousValue: %s", newValue, oldValue);
    },
  },
};
</script>

ParentComponent.Vue Here, Properties are passed to the child component using props syntax.

<template>
  <div id="app">
    <ChildComponent :name="asdasdfad" />
    <button @click="name = 'Hello Frank'">Click me</button>
  </div>
</template>

<script>
import { ChildComponent } from "./components/ChildComponent.vue";

export default {
  name: "ParentComponent",
  components: {
    ChildComponent,
  },
  data() {
    return {
      name: "Hello John",
    };
  },
};
</script>

Conclusion

To Sum up, Learn how to listen and watch property changes in the VueJS application.