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

})

相关推荐
namekong82 小时前
清理谷歌浏览器垃圾文件 Chrome “User Data”
前端·chrome
开发者小天3 小时前
调整为 dart-sass 支持的语法,将深度选择器/deep/调整为::v-deep
开发语言·前端·javascript·vue.js·uni-app·sass·1024程序员节
李少兄5 小时前
HTML 表单控件
前端·microsoft·html
学习笔记1016 小时前
第十五章认识Ajax(六)
前端·javascript·ajax
消失的旧时光-19436 小时前
Flutter 异步编程:Future 与 Stream 深度解析
android·前端·flutter
曹牧7 小时前
C# 中的 DateTime.Now.ToString() 方法支持多种预定义的格式字符
前端·c#
勿在浮沙筑高台7 小时前
海龟交易系统R
前端·人工智能·r语言
歪歪1007 小时前
C#如何在数据可视化工具中进行数据筛选?
开发语言·前端·信息可视化·前端框架·c#·visual studio
Captaincc8 小时前
AI 能帮你写代码,但把代码变成软件,还是得靠人
前端·后端·程序员