uniapp vue3 watch监听使用情况

使用setup 语法糖

首先引入watch

import {watch} from 'vue'

使用情况1:监听ref基本数据类型

const data = ref('') //基本数据类型:string | number | boolean | BigInt | Symbol | null | undefined;
watch(data,(newVal, oldVal)=> {
   console.log(`新值是:${newVal}`, `旧值是${oldVal}`);
})

使用情况2:监听ref引用类型

const data = ref({})
watch(data,(newVal, oldVal)=> {
   console.log(`新值是:${newVal}`, `旧值是${oldVal}`);
}, { deep: true }) //需要手动开启深度监视 { deep: true }

使用情况3:监听reactive定义的数据

注意:reactive 默认自动开启了深度监视,并且该深度监视不可通过配置项 { deep: false } 关闭

const data = reactive({})
watch(data,(newVal, oldVal)=> {
   console.log(`新值是:${newVal}`, `旧值是${oldVal}`);
}, { deep: false}) //关闭无效

使用情况4:监听ref或reactive中具体的属性值的变化

注意:不管该属性值是基本数据类型还是引用数据,都建议使用函数形式

const data = reactive({name:''})
watch(()=>data.name,(newVal, oldVal)=> {
   console.log(`新值是:${newVal}`, `旧值是${oldVal}`);
})


const data = ref({age:''})
watch(()=>data.value.age,(newVal, oldVal)=> {
   console.log(`新值是:${newVal}`, `旧值是${oldVal}`);
})


const data = ref({
    config:{
       n:'' 
    }
})
watch(()=>data.value.config,(newVal, oldVal)=> {
   console.log(`新值是:${newVal}`, `旧值是${oldVal}`);
})

使用情况5:监听多个数据

const data1 = reactive({name:''})
const data2 = ref({age:''})
watch([()=>data1.name,()=>data2.value.age],(newVal, oldVal)=> {
   console.log(`新值是:${newVal}`, `旧值是${oldVal}`);
})

参考文章:带你吃透 Vue3 中 侦听器 【watch ,watchEffect】数据监听的使用及注意事项_watcheffect深度监听-CSDN博客

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值