自学内容网 自学内容网

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博客


原文地址:https://blog.csdn.net/m0_67880202/article/details/142848062

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!