How to listen props changes in Vuejs| watch function example


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

Props in vuejs are used to pass values from parent to child component, also called one way binding by default. Some times we want to watch props changes to know what was changed and its previous value.

Props in parents components contains initialled with initial value, Child components use its value as a local value and do the necessary changes.

In vuejs, watch functions provides 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, Property received from parent component and displays on browser.

There is an **watch function **to listen changes which emits old value 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 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>
Similar Posts