为什么shallowReactive和shallowRef深层对象变化时,也会响应式地显示在页面上?

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>

效果图:

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值