随笔 - 12  文章 - 0  评论 - 0  阅读 - 6091

Vue3系列6--watch侦听器和watchEffect高级侦听器

1 watch侦听器

watch 需要侦听特定的数据源,并在单独的回调函数中执行副作用

  • watch第一个参数监听源
  • watch第二个参数回调函数cb(newVal,oldVal)
  • watch第三个参数一个options配置项是一个对
    •   {
    •   immediate:true //是否立即调用一次
    •   deep:true //是否开启深度监听
    •   }

监听Ref 案例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import { ref, watch } from 'vue'
  
let message = ref({
    nav:{
        bar:{
            name:""
        }
    }
})
  
watch(message, (newVal, oldVal) => {
    console.log('新的值----', newVal);
    console.log('旧的值----', oldVal);
},{
    immediate:true,
    deep:true
})

 监听多个ref 注意变成数组:

1
2
3
4
5
6
7
8
9
import { ref, watch ,reactive} from 'vue'
  
let message = ref('')
let message2 = ref('')
  
watch([message,message2], (newVal, oldVal) => {
    console.log('新的值----', newVal);
    console.log('旧的值----', oldVal);
})

监听Reactive:使用reactive监听深层对象开启和不开启deep 效果一样

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import { ref, watch ,reactive} from 'vue'
  
let message = reactive({
    nav:{
        bar:{
            name:""
        }
    }
})
  
watch(message, (newVal, oldVal) => {
    console.log('新的值----', newVal);
    console.log('旧的值----', oldVal);
})

监听reactive 单一值

1
2
3
4
5
6
7
8
9
10
11
12
import { ref, watch ,reactive} from 'vue'
  
let message = reactive({
    name:"",
    name2:""
})
  
  
watch(()=>message.name, (newVal, oldVal) => {
    console.log('新的值----', newVal);
    console.log('旧的值----', oldVal);
})

2 watchEffect高级侦听器

立即执行传入的一个函数,同时响应式追踪其依赖,并在其依赖变更时重新运行该函数。如果用到message 就只会监听message 就是用到几个监听几个 而且是非惰性 会默认调用一次。

1
2
3
4
5
6
let message = ref<string>('')
let message2 = ref<string>('')
 watchEffect(() => {
    //console.log('message', message.value);
    console.log('message2', message2.value);
})

清除副作用:就是在触发监听之前会调用一个函数可以处理你的逻辑例如防抖

1
2
3
4
5
6
7
8
9
10
import { watchEffect, ref } from 'vue'
let message = ref<string>('')
let message2 = ref<string>('')
 watchEffect((oninvalidate) => {
    //console.log('message', message.value);
    oninvalidate(()=>{
         
    })
    console.log('message2', message2.value);
})

停止跟踪 watchEffect 返回一个函数 调用之后将停止更新

1
2
3
4
5
6
7
8
9
10
11
12
13
const stop =  watchEffect((oninvalidate) => {
    //console.log('message', message.value);
    oninvalidate(()=>{
  
    })
    console.log('message2', message2.value);
},{
    flush:"post",// pre:组件更新前执行;sync:强制效果始终同步触发,post:组件更新后执行
    onTrigger () { //onTrigger  可以帮助我们调试 watchEffect
  
    }
})
stop()
posted on   LotusFlower  阅读(224)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示