传递给子组件的Vue.js道具对象未定义

时间:2020-07-31 13:02:02

标签: javascript vue.js parent-child vue-props

我有一个父项和一个子项。父组件直接包括子组件。该子组件需要来自父组件的一些数据。父组件从REST API加载数据。 当子组件尝试对传递的数据执行某些操作时,浏览器在日志中显示错误消息:Cannot read property 'name' of undefined。 当我查看Vue开发人员工具时,可以看到有一个带userInformation对象的对象...

我想使用created()方法直接在子组件中访问数据对象。但是似乎数据传递太慢。我该如何解决?

我的父母

<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>

我的孩子:

<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 个答案:

答案 0 :(得分:1)

您需要像这样使用它:

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

没有this关键字。

相关问题