初学vue3之watch的用法

2,464 阅读1分钟

一、vue3中的wacth的用法有许多小细节需要注意的,接下来总结一下它的各种使用情况,总有一款你会喜欢的。

情况一、监视ref所定义的响应式数据
watch(sum,(newValue,oldValue)=>{
console.log(newValue,oldValue)
})
情况二、监视ref所定义的多个响应式数据
watch([sum,msg],(newValue,oldValue)=>{
console.log(newValue,oldValue)
})
情况三、监视reactive所定义的多个响应式数据,此处无法获取正确的oldValue,会自动开启深度检测,deep配置无效
watch(person,(newValue,oldValue)=>{
console.log(newValue,oldValue)
})
情况四、监视reactive所定义的多个响应式数据中的某个属性
watch(()=>person.name,(newValue,oldValue)=>{
      console.log('newValue',newValue,oldValue)
    })
特殊情况、监视reactive所定义的多个响应式数据中的某个引用类型数据的属性,深度监视有效deep
watch(()=>person.name,(newValue,oldValue)=>{
      console.log('newValue',newValue,oldValue)
    },deep:true)
vue2中watch的用法
watch:{
name(newValue,oldValue){
  console.log('newValue',newValue,oldValue)
}
或者
name:{
hander(newValue,oldValue){
 console.log('newValue',newValue,oldValue)
},
deep:true //true 深度监听
immediate: true
}
}

vue3中的watch用法与vue2中的用法稍微有一些差异,vue3中使用了组合式api,在监听多个属性的时候非常方便,虽然用起来可能还不是很习惯,但是在日后的开发中,vue3会慢慢替代vue2,所以接下来我们需要慢慢习惯vue3的一些属性的用法,慢慢把vue2迁移至vue3中。