Search code examples
vue.jsvuejs3quasar-frameworkquasarv-for

In there a way in Vue v-for to access two elements in each iteration?


I want to show two ConditionCardComponents per slide. I have added two, but I only have access to one(1) condition item in each iteration. The outcome should look like we have two ConditionCardComponents in one slide.enter image description here

This is with the outcome with one card. Imagine the desired outcome as two of these card in each slide.

 <template v-for="(condition, index) in dealData.Conditions" :key="index">
        <q-carousel-slide :name="index" class="row no-wrap slide-card">
          <ConditionCardComponent
            class="full-height full-width"
            :condition-details="condition.Details"
            :condition-status="condition.Status"
          />
          <ConditionCardComponent
            class="full-height full-width"
            :condition-details="condition.Details"
            :condition-status="condition.Status"
          />
        </q-carousel-slide>
      </template>

It is easy to do this with a finite number of hardcoded cards. All I would do is put every two card in one slide and give it a 'col-6' style. The issue is when I am reading from an object.


Solution

  • v-for can't handle this case natively, you will have to create your own data structure for this.

    You can create a computed property being an array of tuples like: [[condition1, condition2], [condition3, condition4], ...]

    <script setup>
    const slides = computed(() => {
      const slides = []
      for(let i = 0; i < dealData.Conditions.length; i += 2) {
        slides.push([dealData.Conditions[i], dealData.Conditions[i+1]])
      }
      return slides
    })
    </script>
    
    <template>
      <template v-for="(conditionsTuple, index) in slides" :key="index">
        <q-carousel-slide :name="index" class="row no-wrap slide-card">
          <ConditionCardComponent
             class="full-height full-width"
             :condition-details="conditionsTuple[0].Details"
             :condition-status="conditionsTuple[0].Status"
           />
           <ConditionCardComponent
              class="full-height full-width"
              :condition-details="conditionsTuple[1].Details"
              :condition-status="conditionsTuple[1].Status"
           />
        </q-carousel-slide>
      </template>
    </template>