【问题标题】:Vue.js props object passed to children component is undefined传递给子组件的 Vue.js 道具对象未定义
【发布时间】:2023-04-08 08:10:01
【问题描述】:

我有一个父组件和一个子组件。父组件直接包含子组件。这个子组件需要来自父组件的一些数据。父组件从 REST API 加载数据。 当子组件尝试对传递的数据执行某些操作时,浏览器会在日志中显示错误消息:Cannot read property 'name' of undefined。 当我查看 Vue Developer Tool 时,我可以看到有一个带有 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>

【问题讨论】:

  • 你试过if ((this.user.course &amp;&amp; this.user.course.name === 'Math') {吗?
  • 现在我试过了。这似乎行得通。谢谢你。但这是最好的做法吗?当用户对象有很多对象,我想检查几个属性时,我必须检查每个属性?
  • 这个if ((this.user &amp;&amp; this.user.course.name === 'Math')就够了,尝试检查整个对象
  • 我在开始时对整个对象进行了尝试,然后我得到了与原始问题中描述的相同的错误。
  • 修改prop如user: { type: Object,default:null }

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


【解决方案1】:

你需要这样使用它:

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

没有this 关键字。

【讨论】:

  • 坦克,但是当我按照你的建议更改代码时,我又遇到了同样的错误。
  • 可能是来自浏览器缓存,清除浏览器缓存再试一次。
  • 那没有成功。与以前相同的错误消息。我清除了缓存,重新启动了 Chrome。
  • 检查您的if声明中是否有该属性。
  • 该属性在if语句中可用,但在底层属性中不可用
猜你喜欢
  • 1970-01-01
  • 2021-11-18
  • 2020-07-03
  • 2021-12-21
  • 2019-07-11
  • 1970-01-01
  • 2017-07-08
  • 1970-01-01
  • 2021-10-15
相关资源
最近更新 更多