Wacth
import {watch,ref,reactive} from 'vue'
setup(){
let sum = ref(0)
let msg = ref(‘您好’)
let person = reactive({
name;‘yoga’,
age:20,
wife:{
name:'yoga1',
age:22
}
})
1:监视ref定义的一个属性:可以监视到新旧属性值
watch(sum,(newValue,oldValue)=>{
console.log(newValue,oldValue)
})
2:监视ref定义的多个属性:可以监视到新旧属性值
watch(sum,(newValue,oldValue)=>{
console.log(newValue,oldValue)
})
watch(msg,(newValue,oldValue)=>{
console.log(newValue,oldValue)
})
可以一起写:
watch([sum,msg],(newValue,oldValue)=>{
console.log(newValue,oldValue) newValue oldValue都是一个数组
},{immediate:true}) 初始化监听,第三个参数
}
3:监视reactive定义的多个属性:不可以监视到旧属性值,默认开启deep:true,深度监视,关闭不了
watch(person,(newValue,oldValue)=>{
console.log(newValue,oldValue)
})
4:监视reactive定义的某一个属性:可以监视到新旧属性值
watch(()=>perosn.name,(newValue,oldValue)=>{
console.log(newValue,oldValue)
})
5:监视reactive定义的某一个属性:可以监视到新旧属性值
watch([()=>perosn.name,()=>person.age],(newValue,oldValue)=>{
console.log(newValue,oldValue)
})
6:监视reactive定义的某一个属性值依然是一个对象:deep有效
watch(()=>perosn.wife,(newValue,oldValue)=>{
console.log(newValue,oldValue)
},{deep:true})
如果是监视ref定义的复杂数据类型,需要监视.value属性 或者直接开启深度监视