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

Time:01-14

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" >
          <ConditionCardComponent
            
            :condition-details="condition.Details"
            :condition-status="condition.Status"
          />
          <ConditionCardComponent
            
            :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.

CodePudding user response:

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" >
      <ConditionCardComponent
         
         :condition-details="conditionsTuple[0].Details"
         :condition-status="conditionsTuple[0].Status"
       />
       <ConditionCardComponent
          
          :condition-details="conditionsTuple[1].Details"
          :condition-status="conditionsTuple[1].Status"
       />
    </q-carousel-slide>
  </template>
</template>

CodePudding user response:

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

  • Related