在测试vue3复杂数据时候,发现父组件数据使用reactive,子组件修改后,数据会丢失响应
let data = reactive({ c: 1 })这种情况会丢失数据
测试案例和修改方法在下面,
1使用 ref
2 把数据包一层 :键值对模式,let data3 = reactive({ data: { c: 1 } }),reactive使得新数据有响应
父组件
<template>
<div>
<div>我是父组件的数据reactive的情况{{ data.c }}</div>
<div>我是父组件的数据reactive多层data的情况{{ data3.data.c }}</div>
<div>我是父组件的数据ref的情况{{ data2.c }}</div>
<ChildDom :data="data" @update:data="cdata" />
</div>
</template>
<script setup>
import { ref, reactive, toRefs, onBeforeMount, onMounted, watchEffect, computed } from 'vue';
let data = reactive({ c: 1 })
let data3 = reactive({ data: { c: 1 } })
let data2 = ref({ c: 1 })
const cdata = (i) => {
data = i
data3.data = i
data2.value = i
console.log(1212, data, data2, i)
}
</script>
<style scoped lang='less'>
</style>
子组件
<template>
<div>
<div>我是子组件数据{{ data.c }}</div>
<div @click="add">子数据+1</div>
</div>
</template>
<script setup>
import { ref, reactive, toRefs, onBeforeMount, onMounted, watchEffect, computed } from 'vue';
const emit = defineEmits(['update:data'])
const props = defineProps({
data: {
// 表单数据
type: Object,
default: () => { }
}
})
const add = () => {
data.c++
emit('update:data', data)
}
const data = reactive(JSON.parse(JSON.stringify(props.data)))
</script>
<style scoped lang='less'>
</style>