current position:Home>In vue3 setup, the data change of the object cannot be observed by the watch, and the reason is unknown

In vue3 setup, the data change of the object cannot be observed by the watch, and the reason is unknown

2022-02-02 21:10:56 CSDN Q & A

The phenomenon and background of the problem

Vue3 setup in watch No data changes were detected for the object

**father.vue**setup() { let testMsgObj = reactive({    person1: {     name: 'person1',     age: 41,    },    person2: {     name: 'person2',     age: 42,    }, })  let testMsg = testMsgObj.person1 const handleSetLineChartData = () => {    testMsg = testMsgObj.person2    console.log(testMsg) }    return {      testMsg,    }}**child.vue**props: { testMsg: Object},setup(props) { let { testMsg } = props watch( () => testMsg, (val) => {   console.log('testMsg---', val)  },{ deep: true })} 
Operation results and error reporting contents

Can't see testMsg Data change

img

My solution ideas and tried methods
What I want to achieve

hope watch Can monitor testMsg become peson2 The data of Now I only see Parent component testMsg Changed the watch It didn't print out It means that no data change is monitored




Refer to the answer 1:

watch It is generally used to monitor the changes of routing parameters .




Refer to the answer 2:



Refer to the answer 3:

let { testMsg } = toRefs(props)




Refer to the answer 4:



Refer to the answer 5:

reacrive The data of , You deconstruct and take data from it , It's not responsive .
have to torefs() Turn around




Refer to the answer 6:



Refer to the answer 7:

Two things to note :

  • 1.watch Listening is responsive data , The original data testMsg It's not responsive , to testMsg add ref That's all right. ;
  • 2. In obtaining props Do not use deconstruction .
// Parent component let testMsg = ref(testMsgObj.person1);const handleSetLineChartData = () => {     testMsg.value = testMsgObj.person2;   };
// Child components watch(() => props.testMsg,(val) => {        console.log("-----", val);      },      { deep: true }    )



Refer to the answer 8:

copyright notice
author[CSDN Q & A],Please bring the original link to reprint, thank you.
https://en.primo.wiki/2022/02/202202022110534159.html

Random recommended