监听proxy对象
const state = reactive({
obj: { name: 'name', age: 18 },
})
1.此时vue3将强制开启deep深度监听
2.当监听值为proxy对象时,oldValue值将出现异常,此时与newValue相同
watch(
() => JSON.parse(JSON.stringify(state.obj)), //解决(改变单一属性的情况下)新值旧值相同问题
(newValue, oldValue) => {
console.log(newValue, oldValue)
},
{ deep: true }
)
监听proxy数据的某个属性
需要将监听值写成函数返回形式,vue3无法直接监听对象的某个属性变化
watch(
() => state.name,
(newValue, oldValue) => {
console.log("newValue",newValue, "oldvalue", oldValue);
}
);
当监听proxy对象的属性为复杂数据类型时,需要开启deep深度监听
const state = reactive({
obj: {
name: 'name',
age: 18,
city: {
hainan: {
haikou: '海口',
},
},
},
})
watch(
() => state.city,
(newvalue, oldvalue) => {
console.log('state.city newvalue', newvalue, 'oldvalue', oldvalue)
},
{
deep: true,
}
)
监听proxy数据的某些属性
watch([() => state.obj.age, () => state.obj.name], (newValue, oldValue) => {
// 此时newValue为数组
console.log("state.obj.age,state.obj.name", newValue, oldValue);
});
监听数组
const state = reactive({
arr: [1, 2, 3, 4, 5],
})
watch(
() => JSON.parse(JSON.stringify(state.arr)),
(now, old) => {
console.log('old', old)
console.log('now', now)
},
{ deep: true }
)
const array = ref([1, 2, 3])
watch(
() => [...array.value],
(now, old) => {
console.log('old', old)
console.log('now', now)
}
)