[Vuejs]-How can I correctly output a card with v-for?

0👍

Boiling it down to what I believe is the crux of the issue: How to make 5 cards with 8 sections each from an array of 40 elements, where section 1 should stand out from the other 7.

My solution:

  1. Use v-for to loop array.length / 8 (one loop for each card).

  2. Make a nested v-for to loop a sliced subarray of the overall array where each slice is a different 8 items.

  3. Use v-if="index % 8 == 0" to differentiate between the first element vs. the other 7.

<template>
  <div>
    <div v-for="i in arr.length / 8" :key="i" class="card">
      <div v-for="(item, j) in subArr(i)" :key="item.id">
        <div v-if="j % 8 == 0" class="section1">{{ item }}</div>
        <div v-else class="section2">{{ item }}</div>
      </div>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      arr: [],
    };
  },
  methods: {
    subArr(i) {
      const start = (i - 1) * 8;
      return this.arr.slice(start, start + 8);
    },
  },
  created() {
    for (let i = 0; i < 40; i++) {
      this.arr.push({ id: i });
    }
  },
};
</script>

<style>
.card {
  margin: 20px;
  border: 2px solid blue;
  width: 50vw;
}
.section1 {
  background-color: darkolivegreen;
}
.section2 {
  background-color: darkcyan;
}
</style>

Stackblitz example

Leave a comment