Tips for utilizing a vue.js nested for loop with two arrays using v-for

The issue has been resolved, and both my parent view and child component code are now correct and functioning properly I am using Vue.js with the goal of iterating similarly to a nested for loop to display a matrix table. Initially, I tried to achieve this by using a nested v-for loop but encountered difficulties in making it work.

The data used to construct the table consists of dates forming a schedule, each retrieved from a schedule collection in MongoDB. Each day, all teams have a match against another team, and the match data for each team is stored in a schedule array within each document.

To simplify the process and accomplish this task, I created a schedule table containing all team schedules in the parent view, which I passed as a property to the child component to streamline the v-for coding.

The logic for what I'm aiming to do in the child component follows a traditional pattern:

for(const i=0; i<schedules.length; i++) {
for(const j=0; j<weeks.length; j++) {
  console.log("This match is " + schedule[i] + " on " + week[j]) 

I attempted two strategies in the child component without success:

1.) Wrapping a v-for inside a div:

<div v-for="(schedule,j) in schedules" :key="j">
        <sui-table-cell v-for="(number, i) in weeks" :key="i">
        {{schedules[schedule][i].team}}
        </sui-table-cell>
</div>      

2.) Wrapping a v-for inside a template (this code does not compile):

<template v-for="schedule in schedules">
        <sui-table-cell v-for="(number, i) in weeks" :key="i">
        {{schedules[schedule][i].team}}
        </sui-table-cell>
</template>    

The expected data should resemble the image below (click on the link to see where I encounter issues with iteration):

Correct View Of Data

Parent view template.

<template>
  <div>
    <h1 class="ui header center aligned">ACL</h1>
    <h4 class="ui header center aligned schedule">
      <em>CRIBBAGE SCHEDULE</em>
    </h4>
    <sui-table id="standings" class="celled table center aligned">
      <inner-table :weeks="totalWeeks" :allPlayers="allPlayers" />
    </sui-table>
  </div>
</template>
<script>
import TableForm from "./TableForm.vue";
import { api } from "../../../helpers/helpers.js";
export default {
  name: "schedule-header",
  components: { "inner-table": TableForm },
  data() {
    return {
      totalWeeks: [],
      allDates: [],
      allPlayers: []
    };
  },
  async mounted() {
    this.totalWeeks = await api.getTotalWeeks();
    this.allDates = await api.getAllDates();
    this.allPlayers = await api.getTeams();
  }
};
</script>
<style scoped>
h4.schedule {
  color: brown;
}
</style>

Child Component:

<template>
  <div>
    <sui-table-header>
      <sui-table-row>
        <sui-table-header-cell></sui-table-header-cell>
        <sui-table-header-cell>TEAMS</sui-table-header-cell>
        <sui-table-header-cell v-for="(number, i) in weeks" :key="i">WK{{i+1}}</sui-table-header-cell>
      </sui-table-row>
      <sui-table-row>
        <sui-table-cell></sui-table-cell>
        <sui-table-cell></sui-table-cell>
        <sui-table-cell v-for="(number, i) in weeks" :key="i">{{ number.gameDate.substring(0,10) }}</sui-table-cell>
      </sui-table-row>
    </sui-table-header>
    <sui-table-row v-for="(player, i) in allPlayers" :key="i">
      <sui-table-cell>{{i+1}}</sui-table-cell>
      <sui-table-cell>{{ player.player1 }}&{{player.player2}}</sui-table-cell>
      <sui-table-cell v-for="(week, j) in weeks" :key="j">{{player.schedule[j]}}</sui-table-cell>
    </sui-table-row>
  </div>
</template>

<script>
export default {
  props: ["weeks", "allPlayers"]
};
</script>

Answer №1

In Vue, the key property is used to distinguish between components and prevent unnecessary rendering. By using :key="i" in your code, Vue interprets all sui-table-cell with the key i as identical, resulting in repeats. To avoid this, it's important to provide unique keys.

Although the code may function as intended, it is not advisable to use the index as a key. It is recommended to implement a more effective keying strategy.

<sui-table-row v-for="(player, i) in allPlayers" :key="i">
      <sui-table-cell>{{i+1}}</sui-table-cell>
      <sui-table-cell>{{ player.player1 }}&{{player.player2}}</sui-table-cell>
      <div v-for="(schedule,j) in schedules" :key="j">
        <sui-table-cell v-for="(number, i) in weeks" :key="`${j}_${i}`">
          {{schedules[j][i]}}
        </sui-table-cell>
      </div>
</sui-table-row>

Sample data:

{
    schedules: [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],[2,3,4,5,6,7,8,9,1]]
    weeks: [1/1,1/7,1/14,1/21,1/28,2/5,2/12,2/19,2/25,3/3]
}

The solution involving the template will not be effective, as the template portion is never rendered. It is primarily used when utilizing v-for for multiple internal elements like:

<template v-for="...">
 <h1></h1>
 <p></p>
</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

Scroll bar malfunction in Highcharts

I am struggling to get the scroll bar working so that all categories can be displayed. I have tried different approaches but haven't been able to figure out where I'm going wrong. See the code in action here: http://jsfiddle.net/manraj/7racxxu0/ ...

The HTML elements in my JSX code seem to constantly shift around whenever I resize my webpage

Using react.js, I'm currently developing a website that appears like this before resizing: pre-resize_screenshot_website However, upon vertical or diagonal resizing, the layout becomes distorted especially in the 'availability search bar' ...

Internet Explorer terminates AJAX requests

When I send a request to the server using Ajax and JQuery, it returns more than 2000 records (approximately 16,000 records). In Google Chrome, the call is executed although it takes about 40 seconds. However, in Internet Explorer 11, the execution gets ca ...

A guide on incorporating and utilizing third-party Cordova plugins in Ionic 5

Attempting to implement this plugin in my Ionic 5 application: https://www.npmjs.com/package/cordova-plugin-k-nfc-acr122u I have added the plugin using cordova plugin add cordova-plugin-k-nfc-acr122u but I am unsure of how to use it. The plugin declares: ...

How to dynamically bind items in vuejs

I have a basic select that I would like to bind to an array. My framework is Vuetify, but this issue is common across platforms. <v-select v-bind:items="physicianListSpeciality" > </v-select> Now I want to use the same select for multiple arr ...

The selectors in NgRx store are failing to retrieve data from the main global store

As I delve into the world of ngrx, I find myself struggling to fully understand and implement it effectively within my application. Recently, I integrated ngrx version 8.3 into my project in hopes of organizing my state management efficiently. My goal is ...

Check if the value is a string and contains a floating point number; if so, parse and format the float

I need to work on formatting decimal values returned by an API that only responds with strings. The requirement is to add a leading zero but no trailing zeros to any decimal value in the string. If the value is not a float, it should remain unchanged. For ...

QuickFit, the jQuery plugin, automatically adjusts the size of text that is too large

I have incorporated the QuickFit library into my website to automatically resize text. However, I am running into an issue where the text is exceeding the boundaries of its containing div with a fixed size. This is something I need to rectify. This is ho ...

Analyzing data visualization within CSS styling

I have the desire to create something similar to this, but I am unsure of where to start. Although I have a concept in mind, I am struggling to make it functional and visually appealing. <div id="data"> <div id="men" class="shape"></di ...

Converting Excel sheets to JSON using Vue.js

Struggling with reading excel files in vue.js as the memory usage spikes to 5GB after processing a small file. Need help converting the file to JSON format. Tried various options mentioned in the documentation but encountered different errors. Also checked ...

Leveraging jQuery plugins within an AngularJs application

I am currently trying to implement the tinyColorPicker plugin from here in my Angular app, but I am facing difficulties with it. An error message keeps appearing: TypeError: element.colorPicker is not a function In my index.html file, I have included th ...

Receive the most recent query in a Nuxt plugin following the completion of page loading

So, here's the issue - I have a plugin containing some functions that are supposed to update URL queries. However, every time I run $global.changePage(2) or $global.changeLimit(2), the console.log(query) outputs an empty object and doesn't show t ...

Troubleshooting ASP.NET Ajax Error Code 0

Starting from scratch with asp.net and hoping to incorporate infinite scrolling using jQuery Ajax and ASP.NET MVC. Here's the progress so far: <div id="container"></div> <div id="progress" style="display:none"> <h4>Loading ...

How to save array data to a text file using node.js

I have an array containing values that I want to write to a text file using the following code. while(filedataarr.length>0) { firstelement = filedataarr.shift(); //console.log(firstelement); fs.appendFile("D:\\Temp& ...

Looking for assistance on how to use Express JS to make a post request to insert data with an array of objects into a database. Can anyone provide guidance?

While utilizing ExpressJS for serverside functionality, I encountered an issue when making a post call with multiple objects in an array. The error message displayed is as follows: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to t ...

Storing Byte Array in a File using JavaScript

I am working on a Java REST webservice that returns documents as byte array. I am trying to write JavaScript code that will retrieve the response from the webservice and save it to a file for downloading as a PDF. However, when testing my sample code, the ...

Change to a dark theme using React hooks in typescript

Hello, I am new to React and English is not my first language, so please excuse any mistakes. I have been trying to enable a dark mode feature on my website. Most examples I have found involve toggling between dark and light modes where you need to specify ...

Issue encountered in transmitting information from JSP to servlet

I am facing an issue with receiving data from JSP to servlet. I understand that I need to serialize this data using JSON. In my JSP, I have written the following JavaScript code: var myJSONText = JSON.stringify(items); document.getElementById('test&a ...

Protractor functions perfectly on localhost, but encounters a Timeout error when used remotely - the asynchronous callback was not executed within the specified timeout period

Running protractor protractor.conf.js --baseUrl=http://localhost:4200/ executes successfully by filling data, validating elements, etc. However, when attempting to test the same website through a remote URL protractor protractor.conf.js --baseUrl=http://t ...

Video background in webflow not currently randomizing

I want to add a dynamic video background to my website created with Webflow. I attempted to achieve this using Javascript by including the following links: "https://s3.amazonaws.com/webflow-prod-assets/63e4f3713963c5649a7bb382/63f787b42f81b8648e70fed ...