Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Calculadora

0

23
Vistas
Vue3: how to use provide and inject to transmit async data correctly?

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?

7 months ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos