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);

})

相关推荐
铁皮饭盒4 分钟前
Bun.js 集成了 SQL/Redis/S3,为什么 Java/Go/Python 不集成?
javascript
年轻的砖头10 分钟前
以Ajax方式提交整个表单
前端·javascript·ajax
L-影24 分钟前
FastAPI CORS 跨域:Web 世界的“小区门禁”与“访客通行证”
前端·javascript·fastapi
stereohomology29 分钟前
已进入初赛提交Demo的两个项目:(2)单独html钢琴
前端·html·why不coding
源图客36 分钟前
Claude Code基础使用
服务器·前端·数据库
asdzx671 小时前
在 React 中轻松实现 PDF 转 Word:纯前端 WASM 方案实战
前端·react.js·pdf
daols881 小时前
vue 甘特图 vxe-gantt 实现双进度条:计划 vs 实际,支持多级子任务拆分
vue.js·甘特图·vxe-table·vxe-gantt
爱勇宝9 小时前
第 1 章:别把“需求文档”当成真正的需求
前端·后端·程序员
梨子同志10 小时前
常用命令
前端
梨子同志10 小时前
React 状态管理
前端