[Vuejs]-Is it correct to write a code to pass data to child component in vue.js?

0👍

Here, your user variable is filled in asynchronously, so in the beginning you’re sending an empty object as the prop. That said, it shouldn’t fail since {}.name will return undefined and not throw an error.

You have several ways to handle an empty prop in your components:

  1. Create the child component only when you have the full data available:
<Child v-if="user" :data="user" />

This has the benefit to be performant: you don’t ever execute the Child component code until you have the user.

  1. You handle the empty prop within the Child component
<template>
  <div v-if="!data">Loading...</div>
  <div v-else>
    {{ data.name }}
  </div>
</template>

This allows you to show something when the data is missing.


Note: you don’t have to copy the props.data into a ref inside your component unless you want to mutate it. If you do that, you have to use a watcher to update your inner user ref whenever the prop changes too, otherwise the Child component data will be outsynced with the data prop.

0👍

In your case, as you have 3 seconds to fetch data this approach is right.

The issue is that the child component is trying to access the data before it is actually available. This is because the getData() function in the parent component takes 3 seconds to complete and during that time, the user object is still empty. When the child component is created, it tries to access the user object before it has been populated with data, as a result you are getting an error.

Leave a comment