I have a v-for loop on VueJS and I want to wrap the loop elements inside a div in groups of two.
For example:
<div class="xpto" v-for="item in items"> //this div should wrap a maximum of two ponents per time
<ponent :item="item"></ponent>
</div>
What would be the best way to achieve that?
I have a v-for loop on VueJS and I want to wrap the loop elements inside a div in groups of two.
For example:
<div class="xpto" v-for="item in items"> //this div should wrap a maximum of two ponents per time
<ponent :item="item"></ponent>
</div>
What would be the best way to achieve that?
Share Improve this question asked May 5, 2017 at 17:16 felipeecstfelipeecst 1,4153 gold badges19 silver badges34 bronze badges3 Answers
Reset to default 3This seems like something you would really want to do in a puted. I can look at the name of the puted and have a pretty good idea of what it's doing.
puted:{
itemPairs(){
let p = [], copy = [...this.items]
while(copy.length > 0)
p.push(copy.splice(0, 2))
return p
}
}
Template
<div v-for="pair in itemPairs" :key="pair" class="xpto">
<ponent v-for="item in pair"
:item="item"
:key="item">
</ponent>
</div>
Example.
You can achieve this by referencing the index of each item and getting the item from the items
array at the calculated index:
<div
class="xpto"
v-for="n, i in items.length"
v-if="i < items.length / 2"
>
<ponent
v-for="m, j in 2"
v-if="items[i*2+j]"
:item="items[i*2+j]"
></ponent>
</div>
You can use range v-for
<div class="xpto" v-for="n in 2"> //this div should wrap a
maximum of two ponents per time
<ponent :item="items[n-1]"></ponent>
</div>
Vue.js Docs: https://v2.vuejs/v2/guide/list.html#Range-v-for