- watch的套路是:既要指明监视的属性,也要指明监视的回调
- watchEffect的套路是:不用指明监视哪个属性,监视的回调中用到哪个属性,那就监视哪个属性
- watchEffect有点像computed:
- 但computed注重的计算出来的值 (回调函数的返回值),所以必须要写返回值
- 而 watchEffect更注重的是过程 (回调函数的函数体),所以不用写返回值
watch显式指定依赖数据,依赖数据更新时执行回调函数:
watch(sum.value,(newValue,oldValue)=>{
console.log('sum的值变化了',newValue,oldValue)
})
watch(person.age,(newValue,oldValue)=>{
console.log('person的值变化了',newValue,oldValue)
})
watchEffect所指定的回调中用到的数据只要发生变化,则直接重新执行回调:
watchEffect(()=>{
const x1 = sum.value
const x2 = person.age
console.log('watchEffect配置的回调执行了')
})