vue中的ref和reactive默认是深层响应式:
<script setup lang="ts">
import { ref, reactive } from "vue";
// 深层响应式
const count = reactive({
name: 1,
age: { num: 12 },
});
const count1 = ref({ num: 1 });
function add() {
count.age.num++;
count1.value.num++;
}
</script>
<template>
<div class="xiang">
<h2>reactive:{{ count }}</h2>
<h2>ref:{{ count1 }}</h2>
<button @click="add">+</button>
</div>
</template>
<style lang="less" scoped></style>
效果图:
shallowRef和shallowReactive浅层响应式:
<script setup lang="ts">
import { shallowReactive, shallowRef } from "vue";
// 浅层响应式
const count = shallowReactive({
name: 1,
age: { num: 12 },
});
const count1 = shallowRef({ num: 1 });
//改动点:shallowReactive, shallowRef
function add() {
count.age.num++;
count1.value.num++;
}
</script>
<template>
<div class="xiang">
<h2>reactive:{{ count }}</h2>
<h2>ref:{{ count1 }}</h2>
<button @click="add">+</button>
</div>
</template>
<style lang="less" scoped></style>
效果图:
怪异现象:
<script setup lang="ts">
import { shallowReactive, shallowRef } from "vue";
// 浅层响应式
const count = shallowReactive({
name: 1,
age: { num: 12 },
});
const count1 = shallowRef({ num: 1 });
function add() {
count.age.num++;
count1.value.num++;
count.name++;//改动点:修改第一层的数据
}
</script>
<template>
<div class="xiang">
<h2>reactive:{{ count }}</h2>
<h2>ref:{{ count1 }}</h2>
<button @click="add">+</button>
</div>
</template>
<style lang="less" scoped></style>
效果:造成所有数据都是响应式的假象。
这里同样是浅层响应式,只是在按钮处多添加一个第一层name数据的改变,整个数据都会改变,造成count.age.num也是响应式的假象。
因为count.name的改变造成了页面的更新,导致count.age.num也会改变。
<script setup lang="ts">
import { shallowReactive, shallowRef } from "vue";
// 浅层响应式
const count = shallowReactive({
name: 1,
age: { num: 12 },
});
const count1 = shallowRef({ num: 1 });
function add() {
count.age.num++;
count1.value.num++;
}
// 添加一个按钮只改变第一层数据
function add1() {
count.name++;
}
</script>
<template>
<div class="xiang">
<h2>reactive:{{ count }}</h2>
<h2>ref:{{ count1 }}</h2>
<button @click="add">+</button>
<button @click="add1">++</button>
</div>
</template>
<style lang="less" scoped></style>
效果图: