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

})

相关推荐
daols886 小时前
vue vxe-table 自适应列宽,根据内容自适应宽度的2种使用方式
vue.js·vxe-table
小小小小宇6 小时前
虚拟列表兼容老DOM操作
前端
悦悦子a啊6 小时前
Python之--基本知识
开发语言·前端·python
安全系统学习7 小时前
系统安全之大模型案例分析
前端·安全·web安全·网络安全·xss
涛哥码咖7 小时前
chrome安装AXURE插件后无效
前端·chrome·axure
OEC小胖胖8 小时前
告别 undefined is not a function:TypeScript 前端开发优势与实践指南
前端·javascript·typescript·web
行云&流水8 小时前
Vue3 Lifecycle Hooks
前端·javascript·vue.js
Sally璐璐8 小时前
零基础学HTML和CSS:网页设计入门
前端·css
老虎06278 小时前
JavaWeb(苍穹外卖)--学习笔记04(前端:HTML,CSS,JavaScript)
前端·javascript·css·笔记·学习·html
三水气象台8 小时前
用户中心Vue3网页开发(1.0版)
javascript·css·vue.js·typescript·前端框架·html·anti-design-vue