shallowReactive似乎不起作用

来源:8-6 Vue3 响应式数据- reactive

慕数据2053472

2023-08-03

请假老师,为什么用了shallowReactive, 但点击modify时候,深层次friend.age仍旧被修改了,thanks!

<script setup>
import { reactive, ref, shallowReactive } from 'vue';

const profile = {
    name: "daniel",
    age: 18,
    friend: {
        name: "karen",
        age: 22
    }
}

// const myProfile = ref(profile)
// const myProfile = reactive(profile)
const myProfile = shallowReactive(
    {
        name: "daniel",
        age: 18,
        friend: {
            name: "karen",
            age: 1
        }
    }
)
const modify = () => {
    myProfile.age = myProfile.age + '1'
    myProfile.friend.age = myProfile.friend.age + '1'
}
</script>

<template>
<P> HELLO </P>
<p>{{ myProfile }}</p>
<button @click="modify">Modify</button>
</template>
写回答

1回答

coder_monkey

2023-08-03

myProfile.age = myProfile.age + '1' 这句注释掉再次点击看效果

0
1
慕数据2053472
明白了,要用两个button去触发两个方法,分别修改第一层数据和深层数据,这样深层数据不会被修改!
2023-08-03
共1条回复

Vue3+Uni+Node+MySQL 从零实现跨端小程序的全栈应用

小程序、 Vue3、Uni、NodeJs,全新300+技术点,实现跨端全栈应用

274 学习 · 155 问题

查看课程