gpt4 book ai didi

javascript - 如何在 Vue 和 Axios 中循环访问 API 端点 JSON 对象?

转载 作者:行者123 更新时间:2023-12-02 23:24:33 25 4
gpt4 key购买 nike

我有一个 API 端点,它是一个 JSON 对象。我正在使用 Axios 和 Vuejs 将数据提取到 DOM 中,但我只能获取整个对象。当我尝试使用 v-for 指令进行循环时,它不会输出对象中的特定项目。

我使用 Axios 获取数据,如下所示:

export default {
name: 'Reviews',
props: {
title: String
},
data(){
return {
info: []
}
},
// Life cycle hook that calls axios
mounted(){
axios.get('http://dev.muvtravel.com/index.php/explore/test?tripid=6590').then(response => {
console.log(response.data)
this.info = response.data
})
}
}

然后尝试使用v-for循环

<div v-for="(item, index) in info" :key="index">
{{ item.establishment_address }}
{{ item.phone }}
</div>
<template>
<div class="reviews container-fluid">
<h1 class="text-center">{{ title }}</h1>
<b-container>
<b-row>
<b-col cols="12" sm="12" md="12" lg="4" xl="4">
Column 1
</b-col>

<b-col cols="12" sm="12" md="12" lg="8" xl="8">
Column 2
</b-col>
</b-row>
</b-container>

<div v-for="(item, index) in info" :key="index">
{{ item.establishment_address }}
{{ item.phone }}
</div>
</div>
</template>

<script>
import axios from 'axios';

export default {
name: 'Reviews',
props: {
title: String
},
data(){
return {
info: []
}
},
// Life cycle hook that calls axios
mounted(){
axios.get('http://dev.muvtravel.com/index.php/explore/test?tripid=6590').then(response => {
console.log(response.data)
this.info = response.data
})
}
}
</script>

<style scoped lang="scss">

</style>

任何帮助将不胜感激

最佳答案

因此,我检查了代码中的 API 端点是否公开开放 - 确实如此。

从你的有效负载来看,你的代码不起作用的原因是你试图迭代一个对象。您返回的 data 对象是来自该 API 端点的完整负载,它是一个对象 {"success": true, "data": [...]"}.

为了更清楚地说明我正在谈论的内容,这里有一个您可以运行的 fetch 示例:

fetch(yourAPIEndpoint).then(res => res.json()).then(data => console.log(data));

当我运行它时,它会将其打印到控制台:

{success: true, data: Array(15)}

当我编辑上面的 console.log 来输出 data.data 时,如下所示:

fetch(yourAPIEndpoint).then(res => res.json()).then(data => console.log(data.data));

我得到了您尝试设置的位置数组。

TL;DR:您需要设置this.info = response.data.data

祝你编码愉快!

关于javascript - 如何在 Vue 和 Axios 中循环访问 API 端点 JSON 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56796337/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com