In the mounted method, the props value of Nuxt 3 was not received for the first time.
P粉418351692
P粉418351692 2023-07-19 17:47:03
0
1
553

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粉418351692
P粉418351692

reply all(1)
P粉041856955

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);
}); 
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!