LoginSignup
5
3

More than 3 years have passed since last update.

【Vue.js】v-forで配列をn個ずつ描画する

Last updated at Posted at 2020-02-10

やりたいこと

kiji.jpg

このように、配列をn個(今回は3個)並べたら改行したい。
前提:配列はAPI等で受け取るデータで、何個来るかわからない。

v-forで描画するまでやってる記事は見かけなかったのでメモです。

そのままv-for

<template>
  <div>
    <div v-for="(item, index) in array" :key="index">
      <li>{{ item }}</li>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      array: [
        'AMETHYST',
        'BLUE-SAPPHIRE',
        'CITRIN',
        'DIAMOND',
        ...
      ]
    }
  }
}
</script>

配列分割して3個ずつv-for

computedで配列を3個ずつに分割し、それをさらに配列に入れたものを作ります。
配列の中に配列を作るイメージ。


computed: {
  groupedArray() {
    const base = this.array.length
    const split_cnt = 3       // 何個ずつに分割するか
    const grouped_array = []
    for (let i=0; i<Math.ceil(base/split_cnt); i++) {
      let multiple_cnt = i * split_cnt  // 3の倍数
      // (i * 3)番目から(i * 3 + 3)番目まで取得
      let result = this.array.slice(multiple_cnt, multiple_cnt + split_cnt) 
      grouped_array.push(result)
    }
    return grouped_array
    // [
    //   ["AMETHYST", "BLUE-SAPPHIRE", "CITRIN"],
    //   ["DIAMOND", "EMERALD", "FIRE-OPAL"], ...
    // ]
  }
}

外側の配列でv-forし、その中で内側の配列をv-forします(伝われ)。

<div v-for="(items, index) in groupedArray" :key="index">
  <li v-for="(item, index) in items" :key="index">
    {{ item }}
  </li>
</div>

おわり。

さいごに

画像をサムネイル表示するときに使いました。
みなさまのご参考になれば幸いです。

参考記事

配列をn個ずつの配列に分割して、それをまとめた配列を作る

5
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
3