How to listen for props changes in VueJS?
This article is about how to listen for prop changes in vue. We will be vuejs watcher or watch property to listen for any changes in props.
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:
Related Topics:
Related Posts
How to pass data from parent component to child using props in Vue
Find out how to send data from parent component to child component using props in Vue.
Execute a function from child component in Vue
Find out how we can execute a function in the parent component from the child component using emit function in Vue.
Pass multiple objects as props in Vue
Short tutorial on how to pass multiple objects as props to a child component from parent in vue using v-for directive.
How to pass multiple props to component in Vue
Short article on how to pass multiple props to a component in vue using v-bind.
