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

This post provides an example of how to listen to prop changes in a Vue.js component.

Vue.js: Listening and Watching Prop Changes

Props in Vue.js are utilized to pass values from parent to child components, establishing a default one-way binding. While props in parent components are initialized with an initial value, child components use these values as local values, making necessary adjustments.

In Vue.js, watch functions are used to monitor changes.

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

Let’s consider ChildComponent.vue.

In this file, the parent component receives a property and displays it in the browser. There is a watch function that listens to changes, emitting both old 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 Now, let’s explore the ParentComponent.vue. In this file, properties are passed to the child component using prop 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

In conclusion, this tutorial demonstrates how to effectively listen to and watch property changes in a Vue.js application. Understanding these techniques is important for responsive and reactive development within the Vue.js framework.