[英]How to unwrap data from nested props?
Why my variables after unwrapping from props stops being reactive?为什么我的变量在从 props 展开后停止反应?
I three components - parent, second for displaying and third for updating data depending on input (code is very simplified here).我有三个组件 - 父级,第二个用于显示,第三个用于根据输入更新数据(此处代码非常简化)。
Third component is updating parent via event and that updated value should be passed to child.第三个组件是通过事件更新父级,更新后的值应该传递给子级。 I know that architecture might smell.我知道建筑可能有气味。 I'm not using any store.我没有使用任何商店。
What I would expect is that emit is updating value and on Child1
new value is displayed.我期望的是 emit 正在更新值,并在Child1
上显示新值。 That happen if I do not unwrap unwrapped prop.如果我不打开未包装的道具,就会发生这种情况。
// Parent.vue
<template>
<ChildA :data="data"/>
<ChildB @update-data="updateData"/>
</template>
<script setup>
import { reactive, toRefs } from "vue";
const { data } = toRefs(
reactive({ data: { latestEvent: { status: "fail" } } })
);
const updateData = (event) => {
data.value = event;
};
</script>
// ChildA.vue
<template>
{{ latestStatus }}
</template>
<script setup>
import { computed, toRefs } from "vue";
const props = defineProps({
data: {
type: Object,
default: () => {},
},
});
const { data } = toRefs(props);
const { latestEvent } = data.value;
const latestStatus = computed(() => data.value.latestEvent.status);
// const latestStatus = computed(() => latestEvent.status); THAT'S NOT REACTIVE
</script>
// ChildB.vue
<template>
<select v-model="status" @change="onChange()">
<option value="in progress">in progress</option>
<option value="new">new</option>
<option value="fail">fail</option>
</select>
</template>
<script setup>
import { reactive, ref, toRefs } from "vue";
const status = ref("");
const emit = defineEmits(["updateData"]);
const onChange = () => {
emit(
"updateData",
toRefs(
reactive({
latestEvent: { status: status },
})
)
);
};
</script>
How to make my variables reactive after unwrapping from prop?从 prop 展开后如何使我的变量具有反应性?
I would imagine something like this:我会想象这样的事情:
const { data } = toRefs(props);
const { latestEvent } = toRefs(data);
Since the whole data
and not just data.latestEvent.status
value is changed, destructuring it early like const { latestEvent } = data.value
disables the reactivity.由于更改了整个data
而不仅仅是data.latestEvent.status
值,因此像const { latestEvent } = data.value
一样提前解构它会禁用反应性。 latestEvent
refers data.latestEvent
object that exists at the time when setup function runs. latestEvent
指的是setup data.latestEvent
运行时存在的data.latestEvent object。
What happens here is basically:这里发生的事情基本上是:
let foo = { bar: { baz: 1 } };
let bar = foo.bar;
let baz = foo.bar.baz;
foo.bar = { baz: 2 };
console.log(bar !== foo.bar); // true
console.log(baz === 1); // true
It should always be:它应该始终是:
const latestStatus = computed(() => data.value.latestEvent.status);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.