【发布时间】: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 && this.user.course.name === 'Math') {吗? -
现在我试过了。这似乎行得通。谢谢你。但这是最好的做法吗?当用户对象有很多对象,我想检查几个属性时,我必须检查每个属性?
-
这个
if ((this.user && this.user.course.name === 'Math')就够了,尝试检查整个对象 -
我在开始时对整个对象进行了尝试,然后我得到了与原始问题中描述的相同的错误。
-
修改prop如
user: { type: Object,default:null }
标签: javascript vue.js parent-child vue-props