dayo
dayo

Reputation: 106

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

Upvotes: 1

Views: 1591

Answers (1)

Dan
Dan

Reputation: 63059

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>

Upvotes: 2

Related Questions