Utilize Vue's v-for directive to loop through a deeply nested array retrieved from an API call

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

Answer №1

Implement a nested v-for loop to iterate through data.purchases:

<template>
  <div>
    <div class="card" v-for="data in purchases" :key="data.purchases">
        <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"
                >
                <template v-for="purchase  in data.purchases">
                  <div class="column">Laptop: {{purchase.laptop}}</div>
                  <div class="column">Monitor: {{purchase.monitor}}</div>
               </template>
                </div>
              </div>
            </div>
          </div>
        </div>
    </div>
  </div>
</template>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to retrieve information from the YouTube API v3 for multiple YouTube channels using just one request?

I am currently developing an endpoint to retrieve data for videos from two specific YouTube channels. I am using the fetch() method along with URL requests and would like to continue using this approach. How can I construct a single URL that will return da ...

FireFox is causing issues with both ng-view and Angular functions, rendering them unusable

My AngularJS sample application is running smoothly in Google Chrome, but when I tried to test it in Firefox, I encountered issues with ng-view and other functions not working properly. This is the structure of my application: Index.html <!DOCTYPE ht ...

Identifying proxy-induced errors in the request module of node.js: A step-by-step guide

Is the error being caused by a proxy connection issue? If so, I may need to try using a secondary proxy. I intentionally set the wrong address to trigger an error, and upon checking the error object, I found that it contains {code: 'ECONNRESET'} ...

Having trouble getting the p-columnFilter to work with p-multiSelect in my Primeng Angular table

Could someone assist me in troubleshooting why my multiselect filter is not functioning correctly? The multiSelect displays the different options accurately, showing values from the "direction" column. However, when I select any value from the options, all ...

Vue: Error - Unable to execute _vm.myFunction as it is not a function

I'm currently working on adding a basic button to a .vue file that will log a message to the console. Here's the code I have so far: <template> <div> <button v-on:click="sayHello()">Click me</button> < ...

Creating a fresh shortcut on the selenium IDE

Is there a way to customize shortcuts in Selenium IDE by modifying its code? For instance, I would like to set the shortcut ctrl + p for the action run test case, similar to how the save action is assigned ctrl + s. I've searched for the JavaScript ...

Invoker of middleware and stack functions for Express.js with a focus on capturing the response object

It appears that the expressjs app contains a stack of Layer object Arrays. What function is utilized to pass the I am curious about: When a request is sent from the http client, which function is called first and how are the stack array functions with mi ...

Printing iframe does not display CSS effects

As I work on developing a program that involves the use of iframes, I have encountered an issue with CSS effects not appearing when trying to print the iframe. Despite applying CSS successfully in browsers like IE, Chrome, Mozilla, and Edge, the printed ou ...

Constructing an array in an asynchronous manner while simultaneously iterating through other arrays

In my attempt to create a comprehensive keyword list from the existing keywords, I successfully retrieved them all and displayed them in the debug console. However, I am facing confusion regarding the appropriate time and method to call resolve(taxonomyKe ...

The integration of SignalR client within an AngularJs controller is failing to function properly

My Angular application is set up with routes, but I am having trouble getting Signalr to work properly with them. Without routes, Signalr works fine in both directions from client to server and vice versa. However, when using routes, it seems that Signalr ...

What is the best way to conceal a callback form once it has been successfully submitted?

In my callback form, everything seems to be functioning properly. However, there is a slight issue when the client hits the submit button multiple times. Each time they do so, a notification saying "Your request sent successfully" pops up next to the butto ...

Content of "index.html" in Vue CLI

Every time I execute npm run build, it creates a dist folder containing my app - all well and good, but... Issue at Hand: Upon opening my index.html, I find the <!DOCTYPE>, <head>, <body> tags, whereas in my case, all I really need is t ...

Unable to display child component using VueRouter

Recently, I started delving into VueJS and decided to create a new Vue application using vue-cli. After making a few modifications, this is what my router.js looks like: import Vue from 'vue' import Router from 'vue-router' import Hell ...

Improve the translation animation on an element containing numerous child nodes

Looking for ways to enhance the smoothness of the transition in the "infinity list" animation. While it's just a demo at the moment, the real app will have various elements emerging from each "pin". The main performance bottleneck seems to stem from t ...

Guide on how to have controller wait for promise to be resolved by an Angular service

Currently, I have a service that initiates an AJAX request to the backend. Service: function RetrieveCompanyDataService(options) { this.url = '/company'; this.Companies = undefined; this.CompaniesPromise = ...

Storing data for extended periods in NodeJS

Currently, I have a node server up and running. To maintain its uptime when I'm not actively developing, I utilize npm forever. However, for editing purposes (such as restarting the app upon edits or uploads), I rely on npm nodemon. After restarting ...

Tips for accessing the firebase user's getIdToken method in Next.js after a page reload

Currently, I am developing a Next.js project and implementing user authentication using Firebase's signInWithPhoneNumber method for phone number verification. After successful verification, I receive a Firebase user with the getIdToken method to retri ...

A stylish flyout menu with a sleek li background in jquery

Experimenting with http://tympanus.net/Tutorials/CufonizedFlyOutMenu/, I decided to remove the fly-in descriptions and am now attempting to load the extra li with a style that will "highlight" the li.current-menu-item element. An object is set up as follo ...

Refresh a Particular Section of a Website Without Having to Reload the Entire Page

I have this PHP script that I'm using to read specific phrases from a text file and then display one of them randomly on a webpage. Currently, the only way to see a new random phrase is by refreshing the entire page. I'm wondering if there is a w ...

Encountered an unexpected forward slash while trying to parse JSON using

When passing a file, why does the `parseJSON` function fail? The file is stored in variable a and then I attempt to parse it using `parseJSON`. var a = "/android/contents/img/uploads/img_2A0.png"; var result = jQuery.parseJSON(a); The error being displa ...