1、监听单个数据
const count = ref(1);
const name = ref("张三");
const changeCount = () => {
count.value++;
};
const changeName = () => {
name.value = "李四";
};
watch(count, (newVal, oldVal) => {
console.log(newVal, oldVal);
});
2、监听多个数据
const count = ref(1);
const name = ref("张三");
const changeCount = () => {
count.value++;
};
const changeName = () => {
name.value = "李四";
};
watch([count, name], (newArr, oldArr) => {
console.log(newArr, oldArr);
});
3、立即执行
const count = ref(1);
const name = ref("张三");
const changeCount = () => {
count.value++;
};
const changeName = () => {
name.value = "李四";
};
watch(
[count, name],
(newArr, oldArr) => {
console.log(newArr, oldArr);
},
{
immediate: true,
}
);
4、深度监听
const userInfo = ref({
name: "Tom",
age: 18,
});
const setUserInfo = () => {
userInfo.value.age++;
};
watch(
userInfo,
(newVal) => {
console.log(newVal);
},
{
deep: true,
}
);
5、精确监听某个属性
const userInfo = ref({
name: "Tom",
age: 18,
});
const setUserInfo = () => {
userInfo.value.age++;
};
watch(
() => userInfo.value.age,
(newAge, oldAge) => {
console.log(newAge, oldAge);
}
);