javascript - VueJS - Conditionally wrap inside a div - Stack Overflow

I have a v-for loop on VueJS and I want to wrap the loop elements inside a div in groups of two. For ex

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 badges
Add a ment  | 

3 Answers 3

Reset to default 3

This 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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745411845a4626569.html

相关推荐

  • javascript - VueJS - Conditionally wrap inside a div - Stack Overflow

    I have a v-for loop on VueJS and I want to wrap the loop elements inside a div in groups of two. For ex

    4小时前
    40

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信