0
0

Vueで配列をtable表示するには配列をグループ化する

Last updated at Posted at 2024-07-20

はじめに

Vueで配列をtableに表示ようとしていたのですが、"Element is missing end tag"エラーが出てしまいました。色々試したのですがうまくいかない。

こういうやつ

  • 16個の配列があります。
Array
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ]
  • これを単純にtableで4行4列表示させたい
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
  • vueで以下のように書いてみました。
    v-ifで4の倍数ごとに</tr><tr>を入れるものです。
    これでは"Element is missing end tag"エラーになります。
Column.vue
<template>
  <div>
    <div>{{nArray}}</div>
    <table>
      <tr>
        <template v-for="(n, i) in nArray" :key="i">
          <td>{{n}}</td>
          <template v-if="((i + 1) % 4 === 0) && (i !== 0)">
              <!-- カラム4つごとにtrで閉じたい -->
            </tr><tr>
          </template>
        </template>
      </tr>
    </table>
  </div>
</template>

<script>
export default {
  data() {
    return {
      nArray: [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ], 
    };
  }
};
</script>

Qiitaで質問してみた

cssでの解決方法の回答がありました。

<ul style="display:grid; grid-template-columns:repeat(4,1fr)">
  <li v-for="item in nArray" :key="item" style="list-style:none;">{{item}}</li>
</ul>

うーん、これでもいいのだが…。

chatGPT

「配列の要素を4つごとに新しい行<tr>で閉じるためには、配列をグループ化するのが一般的なアプローチです」だそうです。

Column.vue
<template>
  <div>
    <div>{{ nArray }}</div>
    <div>{{ chunkedArray }}</div>
    <table>
      <tbody>
        <tr v-for="(row, rowIndex) in chunkedArray" :key="rowIndex">
          <td v-for="(n, i) in row" :key="i">{{ n }}</td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<script>
export default {
  data() {
    return {
      nArray: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16],
    };
  },
  computed: {
    chunkedArray() {
      const chunkSize = 4;
      const result = [];
      for (let i = 0; i < this.nArray.length; i += chunkSize) {
        result.push(this.nArray.slice(i, i + chunkSize));
      }
      return result;
    },
  },
};
</script>

なるほど~。vueでは配列をグループ化してから処理するのが一般的なんだって。

chunkedArray
[ [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ], [ 9, 10, 11, 12 ], [ 13, 14, 15, 16 ] ]
0
0
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
0
0