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 小时前
TypeScript枚举类型应用:前后端状态码映射的最简方案
javascript·typescript·状态模式
brzhang4 小时前
我操,终于有人把 AI 大佬们 PUA 程序员的套路给讲明白了!
前端·后端·架构
止观止5 小时前
React虚拟DOM的进化之路
前端·react.js·前端框架·reactjs·react
goms5 小时前
前端项目集成lint-staged
前端·vue·lint-staged
谢尔登5 小时前
【React Natve】NetworkError 和 TouchableOpacity 组件
前端·react.js·前端框架
Lin Hsüeh-ch'in5 小时前
如何彻底禁用 Chrome 自动更新
前端·chrome
augenstern4167 小时前
HTML面试题
前端·html
张可7 小时前
一个KMP/CMP项目的组织结构和集成方式
android·前端·kotlin
G等你下课7 小时前
React 路由懒加载入门:提升首屏性能的第一步
前端·react.js·前端框架
谢尔登8 小时前
【React Native】ScrollView 和 FlatList 组件
javascript·react native·react.js