Vue.js props object passed to children component is undefined

Viewed 1189

I have got a parent and a child component. The parent component includes directly the child component. This child component needs some data from the parent. The parent component loads the data from a REST API. When the children component try to do some action with the passed Data, the Browser shows the error message in log: Cannot read property 'name' of undefined. When I look in the Vue Developer Tool, I can see that there is an object with the userInformation...

I want to access the data object directly in the children component with the created() method. But it seems that the data passing is too slow. How can I solve this?

My Parent:

<template>
    <b-container fluid>
          <p>Parent Stuff.....</p>
          <ChildComponent :user="this.userInformation"></ChildComponent>
    </b-container>
</template>

<script>
    import ChildComponent from "@/views/ChildComponent";

    export default {
        name: "Parent",
        components: {
          ChildComponent
        },
        data() {
          return {
            userInformation: {},
          }
        },
        created() {
          this.fetchUserInformation();
        },
        methods: {
          fetchUserInformation() {
              this.axios({
                method: 'get',
                url: process.env.VUE_APP_BACKEND_USER + '/users?username=abc'
            }).then(response => {
                this.userInformation = response.data[0];
            })
          }
      }
  }
</script>

My Child:

<script>

export default {
  name: "ChildComponent",
  props: {
    user: {
      type: Object
    }
  },
  data() {
    return {
      mathStudent: false
    }
  },
  mounted() {
    this.decideWhichStudent();
  },
  methods: {
    decideWhichStudent() {
      if (this.user.course.name === 'Math') {
        this.mathStudent = true;
      }
    }
  }
}
</script>
1 Answers

You need to use it like this:

<ChildComponent :user="userInformation"></ChildComponent>

Without the this keyword.

Related