上一篇:
vue3 toRef&toRefshttps://blog.csdn.net/qq_42543244/article/details/122715199
本篇文章主要记录vue3的shallowRef,shallowReactive的api;
在默认的情况下,无论是 ref还是reactive都是深度监听,但是深度监听带来的问题是:如果数据量比较大,我们在使用ref reactive,讲原始数据代理为响应式数据,是非常消耗性能的,有些时候对于某些数据我们并不需要深度监听,此时就用到了shallowRef shallowReactive;
shallowRef
<template>
<h2>a1:{{ a1 }}</h2>
<button @click="a1 += 1">改变a1</button>
<h2>a2:{{ a2 }}</h2>
<button @click="a2 += 1">改变a2</button>
<h2>a3:{{ a3.num }}</h2>
<button @click="a3.num += 1">改变a3</button>
<h2>a4:{{ a4.num }}</h2>
<button @click="a4.num += 1">改变a4</button>
</template>
<script>
import { ref, shallowRef } from "vue";
export default {
name: "Demo",
setup() {
/* 当传入的数据类型是基本数据类型的时候,我们可以认为 ref & shallowRef没有什么区别
ref shallowRef的区别主要在于ref处理的数据是对象形式的数据
shallowRef:基本类型会转成为响应式的,对象类型的数据就不再去做响应式了
*/
let a1 = ref(0);
let a2 = shallowRef(0);
let a3 = ref({
num: 0,
});
let a4 = shallowRef({
num: 0,
});
console.log("a1===ref>", a1);
console.log("a2===shallowRef>", a2);
console.log("a3===ref>", a3);
console.log("a4===shallowRef>", a4);
return {
a1,
a2,
a3,
a4,
};
},
};
</script>
注意观察:
shallowReactive
<template>
<h1>data1</h1>
<h2>姓名:{{ name1 }}</h2>
<h2>年龄:{{ age1 }}</h2>
<h2>工作薪酬:{{ job1.j1.money }} K</h2>
<button @click="name1 = '李四'">改变姓名</button>
<button @click="age1 += 1">改变年龄</button>
<button @click="job1.j1.money += 1">改变薪酬</button>
<hr />
<h1>data2</h1>
<h2>姓名:{{ name2 }}</h2>
<h2>年龄:{{ age2 }}</h2>
<h2>工作薪酬:{{ job2.j2.money }} K</h2>
<button @click="name2 = '李四'">改变姓名</button>
<button @click="age2 += 1">改变年龄</button>
<button @click="job2.j2.money += 1">改变薪酬</button>
</template>
<script>
import { reactive, shallowReactive, toRefs } from "vue";
export default {
name: "Demo",
setup() {
/*
shallowReactive:只处理对象最外层属性的响应式(浅响应式)
下方示例中:
data2中的name2,age2都是响应式的数据,job2为不响应数据(数据改变,但是页面显示不改变)
*/
let data1 = reactive({
name1: "张三",
age1: 18,
job1: {
j1: {
money: 10,
},
},
});
let data2 = shallowReactive({
name2: "张三",
age2: 18,
job2: {
j2: {
money: 10,
},
},
});
console.log("data1===reactive>", data1);
console.log("data2===shallowReactive>", data2);
return {
...toRefs(data1),
...toRefs(data2),
};
},
};
</script>
shallowRef & shallowReactive使用场景:
如果有一个对象数据,结构比较深,但只有最外层的数据发生变化====>shallowReactive
如果有一个对象数据,后续功能中不会去更改该对象的属性值,而是生成新的对象来替换===>shallowRef
下一篇:
vue3 readonly&shallowReadonlyhttps://blog.csdn.net/qq_42543244/article/details/122772194