I am using vue3 with axios. And I want to get data on FatherComponent
by axios request:
<!-- Father.vue -->
<script setup>
import { onMounted, ref, provide } from "vue";
import ChildComponent from "@/components/Child.vue";
import { getForm } from "@/api/form";
const formData= ref({});
provide("formData", formData);
async function getData() {
// look like: { key1: { name: 'foo' }, key2: { name: 'bar' } }
let res = await getForm();
formData.value = res;
}
onMounted(() => {
getData();
});
</script>
<template>
<div>
<ChildComponent />
</div>
</template>
And use the formData
in ChildComponent
:
<!-- Child.vue -->
<script setup>
import { inject } from "vue";
const formData = inject("formData");
</script>
<template>
<div>
<div>{{ formData }}</div>
<div>{{ formData.key1 }}</div>
</div>
</template>
It works well, just the first div shows a {}
and the second div is blank before getForm()
has response. But if I try to get key1
's name, it will report a error:
<!-- Cannot read properties of undefined (reading 'name') -->
<div>{{ formData.key1.name }}</div>
I was try to declear key1
in ref()
:
// Father.vue
const formData = ref({ key1: {}, key2: {} });
It works but that is very annoying and is not what I need.
So I want to provide()
the data after response, and ChildComponent
can inject()
the updated data directly, not the default {}
, how can I do?