I'm working on Nuxt 3 and I'm having trouble with props. I am passing an object from parent component to child component via props but when I print these props in console the object seems to be empty but if I put the same console below setTimeout function inside mounted method then It will work fine. Check out the code below for more ideas.
Parent component
<template> <ChildComponent :form-data="formData.childData" /> <script setup> const formData = reactive({ ... ... }); onMounted(() => { const { data, error } = await useFetch("my-api-url"); if (data.value) { formData = data.value; } }); </script> </template>
Subassembly
<template> {{ }} <script setup> const props = defineProps({ formData: { type: Object, required: true, default: "", }, }); onMounted(() => { console.log(props.formData); // **Receiving blank object** setTimeout(() => { console.log(props.formData); // **Receiving perfectly ** }, 1000) }); </script> </template>
I tried using the async function onMounted( async () => { ... }) on onMounted, but it didn't work.
Is there any standard option to use props on onMounted without using setTimeout function? Please help me to resolve this issue.
P粉0418569552023-07-20 15:20:39
Before calling await useFetch("my-api-url") in the parent component, the child component has been mounted, so when useFetch() gets the data, you will get an empty object as props.
If you want to listen when props change, you can use watch:
watch(() => props.formData, (old, new) => {
console.log(new);
});