foreach表行除以5

问题描述 投票:0回答:2

我如何显示每5 <td>创建一个新行的表中的数据?

示例

data: [1,2,3,4,5,6];

component:

<tr v-for="item in data">
   <td>{{item}}</td>
<tr>

预期:

| 1 | 2 | 3 | 4 | 5 |

| 6 |

javascript vue.js vue-cli
2个回答
0
投票

您可以创建computed属性,将数组分为5个项目的大块。然后遍历2D数组并创建行和列]

new Vue({
  el: '#example',
  data: {
    array: [1, 2, 3, 4, 5, 6]
  },
  computed: {
    grouped: function() {
      const n = 5; // chunk size
      const length = Math.ceil(this.array.length / n);
      return Array.from({ length }, (_, i) => this.array.slice(i * n, (i + 1) * n))
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<table id="example">
  <tr v-for="row in grouped">
    <td v-for="column in row">{{column}}</td>
  </tr>
</table>

Chunk code reference


0
投票

    new Vue({
      el: '#root',
      data: {
        origin: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
      },
      computed: {
        chunkedOrigin: function() {
          return this.origin.reduce((result, item, index) => { 
            const chunkIndex = Math.floor(index/5)

            if(!result[chunkIndex]) {
              result[chunkIndex] = [] // start a new chunk
            }
            result[chunkIndex].push(item)
            return result
          }, [])
        }
      }
    })
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>


    <table id="root">
      <tr v-for="row in grouped">
        <td v-for="column in row">{{column}}</td>
      </tr>
    </table>

var origin = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

var result = origin.reduce((result, item, index) => { 
  const chunkIndex = Math.floor(index/5)

  if(!result[chunkIndex]) {
    result[chunkIndex] = [] // start a new chunk
  }

  result[chunkIndex].push(item)

  return result
}, [])

console.log(result); // result: [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]

-1
投票

在vue JS循环中,有另一个参数表示索引。

    <tr v-for="(item,index) in data">
     <td v-if="(index % 5 == 0)">{{item}}</td>
   <tr>

因此您可以使用此索引对其施加条件。例如,使用模数来验证索引是否为5]的倍数>

© www.soinside.com 2019 - 2024. All rights reserved.