最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin2浏览0评论

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

发布评论

评论列表(0)

  1. 暂无评论