Axios 获取请求无法与 Json 数组对象配合使用
2022-07-20
138
我正在尝试从 JSON 中的对象数组中获取第二个 [1] 项目的标题:
{
"@attributes": {
"version": "2.0"
},
"channel": {
"title": "Rust News",
"description": "The latest news posts from Rust",
"lastBuildDate": "Thu, 07 Jul 2022 07:00:00 Z",
"item": [
{
"guid": "https:\/\/rust.facepunch.com\/news\/july-2022-update\/",
"link": "https:\/\/rust.facepunch.com\/news\/july-2022-update\/",
"title": "July Update",
"description": "<img src=\"https:\/\/files.facepunch.com\/paddy\/20220705\/july_2022_header.jpg\"><br\/>Combat balance, faster load times, chat filter and much more!\u00a0\u00a0",
"pubDate": "Thu, 07 Jul 2022 07:00:00 Z"
},
{
"guid": "https:\/\/rust.facepunch.com\/news\/community-update-243\/",
"link": "https:\/\/rust.facepunch.com\/news\/community-update-243\/",
"title": "Community Update 243",
"description": "<img src=\"https:\/\/files.facepunch.com\/errn\/1b1311b1\/FTTfqglWQAMxkzD.jpg\"><br\/>Custom desk mats, Mars monuments, thoughtful poetry, and more!",
"pubDate": "Wed, 15 Jun 2022 12:00:00 Z"
}
...
这是 axios 代码:
mounted() {
this.axios.get("./api/feedRust.php").then(response => {
this.items = response.data.channel;
});
}
使用 response.data.channel 时一切正常,但由于此错误,无法从项目数组中获取任何对象:
Cannot read properties of undefined (reading '1')
HTML/Vuejs 代码:
<div>{{items.item[1].title}}<div>
这里可能出了什么问题?
1个回答
您需要确保使用该属性定义了数据,因为在获取响应数据时,它将尝试访问
items.item
,而
index
中可能不存在该数据。
添加条件语句。
像这样:
<div v-if="items.item && items.item.length > 1">{{items.item[1].title}}<div>
Riyaz Khan
2022-07-20