Vue.js - How to increment the index by value 2 in vue v-for loop?

Viewed 4985

The example code is below: In this code, <ul> executes the loop 7 times, But I need it to print arr[0], arr[1] in the <li> tag respectively. But, in the next time, I want the index value increment by 2, so that it prints arr[2], arr[3] and again increment the index value by 2, index becomes 4 and it prints arr[4] and arr[5] and so on. Thank you in advance for the solution.

<ul class="columns" v-for="index in 7" :key="index">
    <li>
        arr[index]
    </li>
    <li>
        arr[index+1]
    </li>
</ul>
3 Answers

There's no step definition in v-for loop, but you could do the following logic to to achieve what you want :

 <ul class="columns" v-for="index in [...Array(7)].map((_,i)=>i).filter(i=>i%2===0)" :key="index">
        <li>
            {{index}}
        </li>
        <li>
            {{index+1}}
        </li>
    </ul>

but it's very recommended to define a computed property that returns [...Array(7)].map((_,i)=>i).filter(i=>i%2===0) like :

computed:{
  evenNumbers(){
    return [...Array(7)].map((_,i)=>i).filter(i=>i%2===0)
  }

}
<ul class="columns" v-for="index in evenNumbers" :key="index">
        <li>
            {{index}}
        </li>
        <li>
            {{index+1}}
        </li>
    </ul>

[...Array(7)] will give an array of undefined items :

 [undefined,undefined,....]

we use map method which as first parameter the current value which is in this case an undefined value represented by _ (just choosing a short name) and the second parameter which is the current index which we want to return it instead of _ then filter the returned indexes which are multiple of 2 i%2===0

What do you think about this solution (maybe not so elegant, but it will give what you expect to get, I hope):

<template v-for="index in arr" :key="index">
    <ul v-if="index % 2 === 0" class="columns">
        <li>
            {{ arr[index] }}
        </li>
        <li v-if="!!arr[index+1]">
            {{ arr[index+1] }}
        </li>
    </ul>
</template>

try this out

<li>
        arr[index==0?index:(index+index)]
    </li>
    <li>
        arr[index==0?index+1:(index+index+1)]
</li>
Related