简体   繁体   中英

How to loop through an API endpoint JSON Object in Vue & Axios?

I have an API endpoint which is a JSON object. I am using Axios and Vuejs to fetch the data into the DOM, but I am only able to get the whole object. When I tried to loop throught with the v-for directive it doesn't output the specific item in the object.

I fetched the data using Axios like so:

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
    })
  }
}

Then tried loop through using 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>

Any help will be appreciate it

So I checked to see if the API endpoint in your code was publicly open - it is.

From looking at your payload, the reason your code isn't working is because you're trying to iterate on an object. The data object that you're returning is the FULL payload from that API endpoint, which is an object {"success": true, "data": [...]"} .

To more clearly illustrate what I'm talking about, here's an example fetch you can run:

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

When I run that, it prints this to the console:

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

When I edit the console.log above to output data.data like so:

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

I get the array of locations that you are trying to set.

TL;DR: You need to set this.info = response.data.data .

Happy coding!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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