[英]Can't access sub-object in Vue JS 3
I'm pretty new in VueJS and am stuck on the following problem:我对 VueJS 还很陌生,并且遇到了以下问题:
I have a template in which a click on a button loads a new template through router.push
and also sends an ID as data along.我有一个模板,在该模板中,单击按钮可通过
router.push
加载一个新模板,并同时发送一个 ID 作为数据。
The template:模板:
<template>
<div>
{{ content.description }} // Works fine
{{ content.subobject.logo }} // Logo not found
</div>
</template>
In the new template that is being loaded I have the following function for saving the received ID into data:在正在加载的新模板中,我有以下功能将接收到的 ID 保存到数据中:
created: function() {
this.ID = this.$route.params.data.toString()
},
then I have a function in methods which uses this ID to get data via axios/get
:然后我在方法中有一个函数,它使用这个 ID 通过
axios/get
获取数据:
methods: {
getContent: function() {
axios.get("https://api-url.com/" + this.ID)
.then((response) => {
this.content = response.data.data
console.log(response);
}).catch(error => {
console.log("ERRR:: ", error.response.data)
});
}
},
this function is called in mounted:这个函数在mounted中被调用:
mounted: function() {
this.getContent()
}
My data function:我的数据功能:
data: function() {
return {
ID: '',
content: [] as any
}
The data that is being returned by the API looks something like this: API 返回的数据如下所示:
title: "this is the title"
description: "Lorem Ipsum"
subobject: {
logo: "Logo URL"
}
When i use {{ content.title }}
or {{ content.description }}
in my template it shows up fine.当我在模板中使用
{{ content.title }}
或{{ content.description }}
,它显示得很好。 As soon as I use {{ content.subobject.logo }} I'll get an error "logo" not found.一旦我使用 {{ content.subobject.logo }} 我就会得到一个错误“logo” not found 。
The funny thing is, when I have the template opend up and add the {{ content.subobject.logo }}
after the page has loaded, save it, and it hot-reloads, it shows up fine?!有趣的是,当我打开模板并在页面加载后添加
{{ content.subobject.logo }}
,保存它,然后热重新加载,它显示正常吗?!
It seems like the data is not "available" on first load - but how can that be, if {{ content.title }}
works fine?似乎数据在第一次加载时“不可用” - 但如果
{{ content.title }}
工作正常,那怎么可能?
Thanks a lot for any ideas!非常感谢您的任何想法!
The data is initially not available which means that content
is still without inner field values, in order to avoid that add a conditional rendering like :数据最初不可用,这意味着
content
仍然没有内部字段值,以避免添加条件渲染,例如:
<div v-if="content.subobject">{{ content.subobject.logo }}</div>
you could also do :你也可以这样做:
data: function() {
return {
ID: '',
content: null
}
}
<template>
<template v-if="content">
<div >{{ content.subobject.logo }}</div>
<div >{{ content.title }}</div>
</template>
</template>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.