watch函数

与vue2.x中配置功能一致
两个小坑:
监视reactive的响应式数据时:oldvalue无法正常获取,强制开启了深度监视(deep配置无效)
监视reactive定义的响应式数据中某个属性时:deep配置无效
let person = reactive({
name:'张三',
age:18,
sex:'男',
job:{
jip:{
salar:20
}
}
})
// 监视一个reactive响应式的全部属性
watch(person,(newValue)=>{
console.log('person变化了1',newValue)
})
// 监视一个reactive响应式的单个属性、
watch(()=>person.name,(newValue,oldValue)=>{
console.log('person.name变化了2',newValue,oldValue)
})
// 监视一个reactive响应式的某些属性、
watch([()=>person.name,()=>person.age],(newValue,oldValue)=>{
console.log('person.name和person.age变化了3',newValue,oldValue)
})
//监视一个reactive响应式的对象属性
watch(()=>person.job,(newValue)=>{
console.log('person.job变化了4',newValue)
},{deep:true})

 

watchEffect

watch的套路时:既要指明监视的属性,也要指明监视的回调
watchEffect的套路是:不用指明那个属性,监视的回调中用到那个属性,那就监视那个属性。
watchEffect有点像computed:
但computed更注重的是计算出来的值(回调函数的返回值),所以必须要写返回值
而watchEffect更注重的是过程(回调函数的函数体),所以不用写返回值
let person = reactive({
name:'张三',
age:18,
sex:'男',
job:{