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

3👍

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>

1👍

I’ve never heard of that behavior before, but I think the easiest way would be to customize your array for your needs. For example, in your script you could do something like this:

export default: {
 data(){
  myArray : ['1','2','3','4','5','6']
 },
 computed: {
  myCustomizedArray(){
    return this.myArray.reduce((myFinalArray, item, index, wholeArray)=>{
     if(index%2===0){
      return [...myFinalArray, [item, wholeArray[index+1]]]
     }
     return myFinalArray
    }, [])
  }
 }
}

This computed method myCustomizedArray() will return an array of arrays like so

[[1, 2],[3, 4]]

If the length of the array is an odd number it will return last nested array with an undefined value, but I’ll leave that task to you. This is the way I would do it

Leave a comment