Search code examples
javascriptvue.jsvuejs2vue-componentv-for

how to loop through nested json response with vue js


I'm actually a newbie to Vue JS, so i've been having a bit of a problem looping through api responses with v-for here's my html

Get Coins Data

<div v-for="coin in coinsData">{{coinsData.data.coins.name}}</div>

my javascript:

 var app = new Vue({
        el: '#app',
        data: {
            coinsData: []
        },
        methods: {
    getCoinsData() {
      fetch("https://api.coinranking.com/v1/public/coins")
        .then(response => response.json())
        .then(data => (this.coinsData = data));
    }
  }
    })

the response I want to loop through is at https://api.coinranking.com/v1/public/coins Its quite large so I didn't paste it in here :)


Solution

  • Call the method in a lifecycle hook like created. And make sure you get the proper response property; coins is actually 3 levels deep in the response:

    var app = new Vue({
      el: '#app',
      data: {
        coinsData: []
      },
      methods: {
        getCoinsData() {
          fetch("https://api.coinranking.com/v1/public/coins")
            .then(response => response.json())
            .then(json => this.coinsData = json.data.coins);
        }
      },
      created() {
        this.getCoinsData();
      }
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
    <div id="app">
      <div v-for="coin in coinsData">{{ coin.name }}</div>
    </div>