请问一下,如下代码中当changeData
执行后,未触发watch,是为什么?ps:使用注释的那段代码是能够监听到的。
export default {
name: 'App',
setup() {
const stateRef = reactive<any>({
data: {},
});
// const stateRef = reactive<any>({
// data: {a:0},
// });
const changeData = () => {
stateRef.data.a = Math.random();
};
watch(
() => stateRef,
() => {
console.log(stateRef.data.a);
},
{
deep: true,
},
);
return {
changeData,
};
},
}
下面方法也不行,是为什么呢?
export default {
name: 'App',
setup() {
const stateRef = reactive<any>({
data: {},
});
stateRef.data.a = 0; // 新增此行
const changeData = () => {
stateRef.data.a = Math.random();
};
watch(
() => stateRef,
() => {
console.log(stateRef.data.a);
},
{
deep: true,
},
);
return {
changeData,
};
},
}
经过一番搜索找到了答案,官方文档
1、实例化的时候,不存在的属性不是响应式的:

2、参考setup文档
再查看beforeCreate文档
因此,setup执行时,响应式属性已经确定,所以之后添加的属性不是响应式的。