【Vue.js】多次元配列のデータをテーブルにうまいこと表示するには
おはようございます。
驚愕。最後に vue の記事を書いたのが 2021年8月。
うそでしょ。1年半くらい気絶でもしてたんか。
うん。そういうことにしておこう。
気を取り直して、
ちょっと入れ子のデータ配列をテーブルに表示する機会があったので備忘。
何も考えずに tr に v-for を付けてもうまくいかないんですよね。
スポンサーリンク
プログラム
CSS
css/style.css
@charset "UTF-8";
body
{
font-family:Helvetica, 'Helvetica Neue', 'Mplus 1p', 'Hiragino Kaku Gothic Pro', 'ヒラギノ角ゴ Pro W3', Meiryo, メイリオ, Osaka, 'MS PGothic' !important;
font-size:12px;
}
h1,h2,h3,h4,h5,h6,.h1,.h2,.h3,.h4,.h5,.h6
{
font-family:Helvetica, 'Helvetica Neue', 'Mplus 1p', 'Hiragino Kaku Gothic Pro', 'ヒラギノ角ゴ Pro W3', Meiryo, メイリオ, Osaka, 'MS PGothic' !important;
}
div#app .table-container{
height: 400px;
max-height: 400px;
overflow-y: auto;
margin: 10px 0px;
}
html
index.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ja" lang="ja">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>Vue で Hello World</title>
<meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.1/css/all.css">
<link rel="stylesheet" href="css/style.css">
</head>
<body class="hold-transition fixed skin-blue-light sidebar-mini ">
<div class="wrapper" >
<div style="margin: 20px;">
<pre>
Vue.js で データ配列を元にテーブルを動的に生成するサンプル。
入れ子になっているデータ配列を処理する場合、tr に v-for を設定するとうまく出来ない。
template タグを使って疑似的にループさせるとうまく出来る。
</pre>
</div>
<div class="container">
<div class="row">
<div class="col-xs-12">
<div id="app">
<div class="table-container">
<table class="table">
<thead>
<tr>
<th>項目1</th>
<th>項目2</th>
</tr>
</thead>
<tbody>
<template v-for="group in groupList">
<tr style="background: #eee;">
<th colspan="2">{{ group.name }}</th>
</tr>
<template v-for="item in group.itemList">
<tr>
<td>{{ item.item1 }}</td>
<td>{{ item.item2 }}</td>
</tr>
</template>
</template>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="js/script.js"></script>
</body>
</html>
Javascript
js/script.js
/**
* Vueインスタンス生成
*/
const app = new Vue({
el: '#app',
data: {
groupList: [
{ name:'グループ1', itemList:[
{ item1: 'グループ1-1', item2: 'グループ1-2' },
{ item1: 'グループ2-1', item2: 'グループ2-2' }
] },
{ name:'グループ2', itemList:[ { item1: 'グループ2-1', item2: 'グループ2-2' }] },
{ name:'グループ3', itemList:[ { item1: 'グループ3-1', item2: 'グループ3-2' }] },
{ name:'グループ4', itemList:[ { item1: 'グループ4-1', item2: 'グループ4-2' }] },
]
},
methods: {
}
})起動してみる
まとめ
意外と多次元の配列を扱いたいってケース多いと思うんですよね。
超久々の vue.js 記事でしたが、何かのお役に立てれば。
ではでは。
ディスカッション
コメント一覧
まだ、コメントがありません