vue3+ts 第七章(认识watch侦听器)

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

watch第一个参数监听源

watch第二个参数回调函数cb(newVal,oldVal)

watch第三个参数一个options配置项是一个对象{

immediate:true //是否立即调用一次

deep:true //是否开启深度监听

}

监听Ref 案例

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 注意变成数组啦

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 效果一样

import { ref, watch ,reactive} from 'vue'

let message = reactive({

nav:{

bar:{

name:""

}

}

})

watch(message, (newVal, oldVal) => {

console.log('新的值----', newVal);

console.log('旧的值----', oldVal);

})

案例2 监听reactive 单一值

import { ref, watch ,reactive} from 'vue'

let message = reactive({

name:"",

name2:""

})

watch(()=>message.name, (newVal, oldVal) => {

console.log('新的值----', newVal);

console.log('旧的值----', oldVal);

})

相关推荐
仿生狮子5 小时前
把 Git 提交历史变成一条流动的河——Project River
vue.js·设计·vibecoding
LCG元8 小时前
STM32实战:基于STM32F103的Bootloader设计与IAP在线升级
javascript·stm32·嵌入式硬件
xixingzhe29 小时前
idea启动vue项目
java·vue.js·intellij-idea
超级无敌暴龙兽9 小时前
和我一起刷面试题呀
前端·面试
wzl202612139 小时前
企业微信定时群发技术实现与实操指南(原生接口+工具落地)
java·运维·前端·企业微信
小码哥_常9 小时前
Robots.txt:互联网爬虫世界的“隐形规则”
前端
小码哥_常9 小时前
Android开发神器:AndroidAutoSize,轻松搞定屏幕适配
前端
前端一小卒9 小时前
前端工程师的全栈焦虑,我用 60 天治好了
前端·javascript·后端
不停喝水9 小时前
【AI+Cursor】 告别切图仔,拥抱Vibe Coding: AI + Cursor 开启多模态全栈新纪元 (1)
前端·人工智能·后端·ai·ai编程·cursor