Why do my variables stop being reactive after unwrapping from props?
I have three components - a parent component, a second component for display, and a third component for updating data based on input (simplified code here).
The third component updates the parent through an event, and that updated value should be passed to the child. I understand that the architecture might not be ideal as I'm not using any store.
I would expect the emit to update the value and the new value to be displayed on Child1
. This works when I don't unwrap the 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 can I make my variables reactive after unwrapping them from the prop?
I would think something like this could work:
const { data } = toRefs(props);
const { latestEvent } = toRefs(data);