vue3 watchwa watchEffect

Watch monitors the data defined by ref

1.ref data basic data type

let sum=ref0const stopWatch=watch(sum,(new,old)=>{
    
    
If(new>=10){
    
    
stopWatch()
}
console.log(‘sum数据变化了’)
}

2. The ref data is an object type, and what is monitored is the address value of the object. If you want to monitor the changes in the internal attribute values ​​of the object, you need to manually enable in-depth monitoring.

Insert image description here

 let person=ref{
    
    name:’张三’,age:22})

watch(person,(new,old)=>{
    
    
console.log(‘person数据变化了’,new,old)//打印出来的new和old是一样的数据,因为地址没变
}{
    
    deep:true}

3. Monitor the object type data defined by reactive, and in-depth monitoring is enabled by default

![](https://img-blog.csdnimg.cn/direct/d571da5fe2a64da0ad6550db3b6197a3.png#pic_centerInsert image description here

watch(person,(new,old)=>{ console.log('person data has changed', new, old)//The printed new and old are the same data, because the address has not changed })

4. Listen to a certain attribute in the reactive object, and the attribute is a basic data type and needs to be written in a functional form

Insert image description here
Insert image description here

watch(()=>person.name,(new,old)=>{
    
    
console.log(‘person数据变化了’,new,old)//打印出来的new和old是不一样的
}//监听person.car  可以监听到changeC1、changeC2,但监听不到changeCar里的变化
watch(person.car,(new,old)=>{
    
    
console.log(‘person数据变化了’,new,old)//打印出来的new和old是不一样的
}//监听person.car写函数式,即监听地址  不能监听到changeC1、changeC2,但能监听到changeCar里的变化
watch(()=>person.car,(new,old)=>{
    
    
console.log(‘person数据变化了’,new,old)}//监听person.car写函数式,加deep可以监听即监听changeC1、changeC2  也监听到changeCar里的变化
watch(()=>person.car,(new,old)=>{
    
    
console.log(‘person数据变化了’,new,old)}{
    
    deep:true}

Summary: What is monitored is the attributes in the object, so it is best to write functional expressions. Note: If the object monitors the address value, you need to pay attention to the inside of the object, and you need to manually enable in-depth monitoring.

5. Monitor multiple data array forms

watch([()=>person.name,()=>person.car.c1],(new,old)=>{
    
    
console.log(‘person数据变化了’,new,old)
}

watchEffect monitors data

Insert image description here

watchEffect(()=>{
    
    
If(temp.value>=60||height.value>=80){
    
    
  Console.log(‘已达标’)
}
})

Guess you like

Origin blog.csdn.net/lxuanz/article/details/135976528