6.0 vue3 watch监听函数(reactive篇)
作者:互联网
上一篇:
vue3 watch监听函数 (ref篇)https://blog.csdn.net/qq_42543244/article/details/122203802?spm=1001.2014.3001.5501上篇说到的是监听ref声明的数据,今天记录监听reactive声明的数据,其实差别并不是不大,但是其中有一些坑,特此记录,请看代码(注释也要仔细看哦)
<template>
<h1>reactive数据类型</h1>
<h2>姓名:{{ data.name }}</h2>
<h2>年龄:{{ data.age }}</h2>
<h2>爱好:{{ data.hobby }}</h2>
<h2>工作薪酬:{{ data.job.j1.money }} K</h2>
<button @click="data.name = '李四'">改变姓名</button>
<button @click="data.age += 1">改变年龄</button>
<button @click="data.hobby[0] = '踢足球'">改变爱好</button>
<button @click="data.job.j1.money += 1">改变薪酬</button>
</template>
<script>
import { reactive, watch } from "vue";
export default {
name: "Demo",
setup() {
let data = reactive({
name: "张三",
age: 18,
hobby: ["打篮球", "玩游戏", "听音乐"],
job: {
j1: {
money: 10,
},
},
});
// 监听reactive数据
/*
此时是有问题的:oldVal会和newVal数据保持一致,当data里面的任意值改变,都会触发该监听,强制开启深度监听,deep配置在此时是无效的
*/
watch(data, (newVal, oldVal) => {
console.log(newVal, oldVal);
});
// 监听reactive中的某个值
// 基础类型值
watch(
() => data.name,
(newVal, oldVal) => {
console.log(newVal, oldVal);
}
);
// 数组 此时deep的配置生效(此处的oldVal也是有问题的)
watch(
() => data.hobby,
(newVal, oldVal) => {
console.log(newVal, oldVal);
},
{ deep: true }
);
// 对象 此时deep的配置生效(此处的oldVal也是有问题的) 若要监听对象内的money: data.job.j1.money 即可
watch(
() => data.job,
(newVal, oldVal) => {
console.log(newVal, oldVal);
},
{ deep: true }
);
// 监听reactive中的某些值
// 都为基本数据类型 一切正常
watch([() => data.name, () => data.age], (newVal, oldVal) => {
console.log(newVal, oldVal);
});
//基本数据类型+数组/对象 deep有效 基本数据类型oldVal正常 引用数据类型oldVal存在问题
watch(
[() => data.name, () => data.hobby],
(newVal, oldVal) => {
console.log(newVal, oldVal);
},
{ deep: true }
);
//引用数据类型+引用数据类型 deep有效 引用数据类型oldVal存在问题
watch(
[() => data.hobby, () => data.job],
(newVal, oldVal) => {
console.log(newVal, oldVal);
},
{ deep: true }
);
return {
data,
};
},
};
</script>
标签:reactive,watch,deep,newVal,oldVal,6.0,data,监听 来源: https://blog.csdn.net/qq_42543244/article/details/122281029