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数据的变化
希望watch 可以监听 testMsg 变成peson2的数据 现在只看到 父级的组件 testMsg 改变了 watch并没打印出来 说明没监视到数据变化
需要注意两点:
//父组件
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)
})