Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

244
Views
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?

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!