[英]How to loop through an API endpoint JSON Object in Vue & Axios?
我有一個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端點的FULL負載,它是一個對象{"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
。
編碼愉快!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.