繁体   English   中英

如何在Vue和Axios中遍历API端点JSON对象?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM