I've recently embarked on my journey to learn Vue and decided to practice a bit. However, I found myself stuck when trying to work with for-loops.
To better grasp data handling, I created an API and made a call to it. The output of the call looks like this:
[
{
"_id": "ID1",
"customerID": "ASDF",
"purchases": [
{
"laptop": "DELL",
"price": "500"
},
{
"monitor": "DELL",
"price": "200"
}
]
},
{
"_id": "ID2",
"customerID": "FDSA",
"purchases": [
{
"laptop": "MacBook",
"price": "1800"
},
{
"monitor": "DELL",
"price": "300"
}
]
}
]
My goal is to use v-for to iterate through the array of purchases and display its contents for each entry in the JSON.
The Vue template I'm working with is:
<template>
<div>
<div class="card" v-for="data in purchases" :key="data._id">
<div class="card-image">
<div class="card-content">
<div class="media">
<div class="media-content">
<p class="title is-4">PURCHASES</p>
<div
class="columns is-variable is-1-mobile is-0-tablet is-3-desktop is-8-widescreen is-2-fullhd"
>
<div class="column">Laptop: {{data.purchases[0].laptop}}</div>
<div class="column">Monitor: {{data.purchases[0].monitor}}</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</template>
Here's the script in my Vue file:
<script>
import { ref } from "@vue/composition-api";
export default {
setup() {
const purchases = ref([]);
const API_url = "http://localhost:8383/purchases";
async function getData() {
const response = await fetch(API_url);
const json = await response.json();
purchases.value = json;
console.log(purchases);
}
getData();
return {
purchases,
};
},
};
</script>
I understand that I'm only displaying the first element of the array and that leads me to my question - how can I loop through the entire array using v-for?
Your assistance would be greatly appreciated :)