Home > Software design >  What causes this failure to pass an object from the main component to a child component in a Vue 3 a
What causes this failure to pass an object from the main component to a child component in a Vue 3 a

Time:04-10

I am working on a Vue 3 app. I have run into a problem working with a component and one of its <User /> subcomponent.

In App.vue:

<template>
  <Navbar />
  <Sidebar />
  <Content 
    title="Users"
  />
  <Footer />
</template>

<script>
import Navbar from './components/Navbar.vue'
import Content from './components/Content.vue'
import Sidebar from './components/Sidebar.vue'
import Footer from './components/Footer.vue'

export default {
  name: 'App',
  components: {
    Navbar,
    Content,
    Sidebar,
    Footer  
  },

  data() {
    return {
      url: 'https://jsonplaceholder.typicode.com',
      users: [],
    }
  },
  async mounted() {
    // Users
    await this.axios.get(`${this.url}/users`).then((response) => {
      if (response.data.code == 200) {
        this.users = response.data.data;
        console.log(this.users);
      }
    }).catch((errors) => {
      console.log(errors);
    });
  }
}
</script>

In Navbar.vue:

<template>
  <a  href="#">My App</a>
  <User :users='users' />
</template>

<script>
import User from './User.vue'

export default {
  name: 'Navbar',
    components: {
        User
    }
}
</script>

In User.vue, I try to output the user's full name fis way, since typeof(users) retuens object:

<template>
    {{ users.firstName }} {{ users.lastName }}
</template>

<script>
export default {
  name: 'User',
    props: {
    users: Object
  }
}
</script>

The problem

I get this error in the console: Uncaught TypeError: Cannot read properties of undefined (reading 'firstName').

Where is my mistake?

CodePudding user response:

//in Navbar

<template>

  <a  href="#">My App</a>

    <User :users='usersData' />

</template>    

<script>
import User from './User.vue'

export default {
  name: 'Navbar',
    components: {
        User
    },
props:['usersData']
}
</script>

//in App.vue

<template>
  <Navbar :usersData="users" />
  <Sidebar />
  <Content 
    title="Users"
  />
  <Footer />
</template>
  • Related