1 Problem Description
Suppose there is a property a in the child component ChildComponent, with the default value of 0, and its numerical change is monitored through the listener watch. In the parent component ParentComponent, call the child component and assign the value of property a to 1 to pass it to the child component. It is found that the value of a in the child component template is 1, but watch does not listen to the change in the value of property a.
Subcomponent sample code:
<template> <!-- aThe value of1 --> <div>{{ a }}</div> </template> <script setup> import { watch } from 'vue' const props = defineProps({ a: { type: Number, default: 0 } }) watch( () => , (newValue, oldValue) => { // The following information will not be printed in the console ('a has changed', newValue, oldVlue) } ) </script>
Parent component sample code:
<template> <ChildComponent :a="1" /> </template>
2 Causes
Vue official website:watch is lazy to execute by default: callbacks are executed only when the data source changes.
Vue renders the child component first and then the parent component when rendering a template. When the child component is initialized, the value of attribute a is assigned to the default value 0, and the parent component is initialized, passing a=1 to the child component. After the child component receives it, the new value will be overwritten with the original old value and the initialization is completed. Since the subcomponent properties are responsive, the template view will be updated after changing from 0 to 1. This process occurs during the component initialization stage. The watch function is bound for the first time. It does not believe that the data source has changed, so the callback will not be executed.
3 Solutions
Vue providesimmediate
Attribute. After setting this attribute, you can enable the watch function to execute a callback immediately after the first binding to obtain the latest attribute value.
watch( () => , (newValue, oldValue) => { // Print result is a has changed, 1, 0 ('a has changed', newValue, oldVlue) }, { immediate: true } // Add this line)
This is the article about the solution to the Vue3 child component watch cannot monitor the property values passed by the parent component. For more related contents of Vue3 watch cannot monitor the property values passed by the Vue3 watch, please search for my previous article or continue browsing the related articles below. I hope everyone will support me in the future!