Home > Back-end >  How do i iterate over API response in Vue.js?
How do i iterate over API response in Vue.js?

Time:04-08

Hello I'm a noobie in Vue, How do I iterate through this in my template and render it ? I can console log everything but I can't render it on my page.

API URL : https://private-922d75-recruitmenttechnicaltest.apiary-mock.com/customexercises/

I've tried this :

 <div v-for="post in posts" :key="post.id">
    <h2>{{ post.exercises.id }}</h2>
    <h2>{{ post.exercises.name }}</h2>
  </div>

enter image description here

enter image description here

CodePudding user response:

You are very close! :)

See this playground

<script setup>
import { ref, onBeforeMount } from 'vue'
  
const posts = ref([])

onBeforeMount(async () => {
  posts.value = await fetch("https://private-922d75-recruitmenttechnicaltest.apiary-mock.com/customexercises/").then(raw => raw.json()).then(json => json.exercises)
})
</script>

<template>
<div v-for="post in posts" :key="post.id">
    <h2>{{ post.id }}</h2>
    <h2>{{ post.name }}</h2>
  </div>
</template>

CodePudding user response:

As per the API response, exercises is an array of objects. Hence, to access it's object properties you have to iterate over the exercises array.

Demo :

const app = new Vue({
  el: '#app',
  data() {
    return {
      posts: {
        exercises:[{  
          id: "5c10de5792437a5c67e74ba2",
          name: "Pull Up",
        }, {  
          id: "5c0e7f6d41403b024ad987cc",
          name: "Barbell Bicep Curl",
        }]
      }
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <div v-for="post in posts.exercises" :key="post.id">
    <h2>{{ post.id }}</h2>
    <h2>{{ post.name }}</h2>
  </div>
</div>

  • Related