vue watch props
<template>
<div>
<ChildComponent :inputProp="parentData" />
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent,
},
data() {
return {
parentData: 'Initial Value',
};
},
watch: {
parentData(newValue, oldValue) {
console.log('New value:', newValue);
console.log('Old value:', oldValue);
},
},
};
</script>
Explanation:
The
<template>
section contains the structure of the parent Vue component. It includes a<div>
that houses theChildComponent
. The:inputProp
attribute ofChildComponent
is bound to theparentData
property.In the
<script>
section:- The
import
statement brings in theChildComponent
from a file namedChildComponent.vue
. - The Vue component is defined with its
components
property, which includes theChildComponent
. The
data()
method defines theparentData
property with an initial value of'Initial Value'
.The
watch
property within the Vue component defines a watcher for theparentData
property. WheneverparentData
changes, the function inside the watcher is triggered with two parameters:newValue
andoldValue
. In this case, it logs the new and old values to the console usingconsole.log
. ```