Vue3 setup中 watch不到对象的数据变化,不知道什么原因

问题遇到的现象和发生背景

Vue3 setup中 watch不到对象的数据变化

问题相关代码,请勿粘贴截图
**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 })
} 
运行结果及报错内容

无法看到 testMsg数据的变化

img

我的解答思路和尝试过的方法
我想要达到的结果

希望watch 可以监听 testMsg 变成peson2的数据 现在只看到 父级的组件 testMsg 改变了 watch并没打印出来 说明没监视到数据变化

需要注意两点:

  • 1.watch监听是响应式数据,原数据testMsg就不是响应式的,给testMsg加上ref就可以了;
  • 2.在获取props时不要使用解构。
//父组件
let testMsg = ref(testMsgObj.person1);
const handleSetLineChartData = () => {
     testMsg.value = testMsgObj.person2;
   };
//子组件
watch(() => props.testMsg,(val) => {
        console.log("-----", val);
      },
      { deep: true }
    )

watch一般用来监听路由参数的变化。

let { testMsg } = toRefs(props)

reacrive的数据,你解构从里面拿数据,拿出来的不是响应式的。
得torefs()转一下

发现问题了
1 testMsg 必须是 ref 模式
2 watch 只能 props.testMsg (不要使用解构)
多谢 超小少 指点 之前绕进去了

let testMsg = ref(testMsgObj.person1)
const handleSetLineChartData = (type) => { 
 testMsg.value = testMsgObj.person2
}

watch(
 () => props.testMsg, (val) => {
   console.log('watch--', val)
})