19
18

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Vue.jsのv-forでネスト(入れ子)したい

Posted at

##はじめに
Vue.jsを学習している中でv-forをネストする方法でつまづいたので今回記事としてまとめてみました。

##基本的なv-forの使い方
dataの値が配列の場合、v-forを使用することでリスト形式で表示することができます。

sample.js
var sample = new Vue({
	el: '#sample',
	data: {
		message: 'v-for基本',
		items: ['item1', 'item2', 'item3']
	}
})

sample.html
<div id="sample">
	<h1>{{ message }}</h1>
	<ul>
		<li v-for="item in items">{{ item }}</li>
	</ul>
</div>

結果↓
スクリーンショット 2019-02-25 15.32.17.png

##今回やりたいこと(完成形)
さっそく本題へ!
ネストのリストの完成形はこちらです。↓
スクリーンショット 2019-02-25 15.30.48.png

##v-forで入れ子(ネスト)を実装

sample2.js
var sample2 = new Vue({
	el: '#sample2',
	data: {
		message: 'v-forでネスト',
		categorys:[
			{name:'哺乳類', animals:['', 'ねこ', 'さる', 'パンダ']},
			{name:'鳥類', animals: ['ニワトリ', 'アヒル', 'カラス', 'すずめ']},
			{name:'爬虫類', animals: ['わに', 'トカゲ', 'へび', 'かめ']}
		]
	}
})
sample2.html
<div id="sample2">
	<h1>{{ message }}</h1>

	<ul v-for='category in categorys'>
		<li>
			{{ category.name }}
			<ul>
				<li v-for="animal in category.animals">{{ animal }}</li>
			</ul>
		</li>
	</ul>
</div>

ネストしたリストを表示することができました〜♪

##解説
もう少し詳しくcategorys配列の中身を見てみたいと思います。

<ul v-for='category in categorys'>
	<p>{{ category }}</p>
	<li>
		{{ category.name }}
		<ul>
			{{ category.animals }}
			<li v-for="animal in category.animals">{{ animal }}</li>
		</ul>
	</li>
</ul>
スクリーンショット 2019-02-25 17.09.57.png

上記の結果よりネストを実現したい場合
v-for="category in categorys"で要素を取り出す。
{ category.key名 }を指定することでkeyに紐づいたvalue値を1つずつ取り出す。
catogory.animalsは配列なのでさらにv-for="animal in category.animals"で1つずつvalue値を取り出す。

##まとめ
v-forを利用してネストで表示するのだいぶ苦戦しました。
解説」でもいろいろデータを表示して試している通り実際に表示して動作を確認しながら書くと理解が深まると思います。

19
18
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
19
18

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?