VUE中v-for的4中使用方式

larQ發表於2019-03-05

v-for四種使用方式

v-for 是vue的 迴圈指令,用於遍歷,有以下四種方式

  • 遍歷普通陣列
  • 遍歷物件陣列
  • 遍歷物件
  • 遍歷數字

還有一個注意的v-for迴圈中 key的指定 ,這是必要的

v-for 遍歷普通陣列

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script src="../lib/vue.js"></script>
	</head>
	<body>
		<div id="app">
			<!-- <p>{{list[0]}}</p>
			<p>{{list[1]}}</p>
			<p>{{list[2]}}</p>
			<p>{{list[3]}}</p> -->
			<!-- index 為索引 ,item為每一項-->
			<p v-for="(item,index) in list">{{item}}</p>
		</div>
	</body>
	<script>
		var app = new Vue({
			el: '#app',
			data: {
				list:[1,2,3,4,5,6]
			},
			methods:{
				
			}
		})
	</script>
</html>

複製程式碼

v-for 遍歷物件陣列

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script src="../lib/vue.js"></script>
	</head>
	<body>
		<div id="app">			
			<p v-for="(item,index) in list">id:{{item.id}} === name: {{item.name}}===索引:{{index}}</p>
		</div>
	</body>
	<script>
		var app = new Vue({
			el: '#app',
			data: {
				list: [
					{id:1,name:'lj1'},
					{id:2,name:'lj2'},
					{id:3,name:'lj3'}
				]
			}
		})
	</script>
</html>

複製程式碼

v-for 遍歷物件

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script src="../lib/vue.js"></script>
	</head>
	<body>
		<div id="app">			
			<p v-for="(val,key,index) in user">值:{{val}}=== 鍵:{{key}}===索引:{{index}}</p>
		</div>
	</body>
	<script>
		var app = new Vue({
			el: '#app',
			data: {
				user: {
					id:1,
					name:'lj'
				}
			}
		})
	</script>
</html>

複製程式碼

v-for遍歷 數字

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script src="../lib/vue.js"></script>
	</head>
	<body>
		<div id="app">	
			<!-- 遍歷數字時 從1開始,但索引還是從0開始 -->	
			<p v-for="(count,index) in 10">值:{{count}}===索引:{{index}}</p>
		</div>
	</body>
	<script>
		var app = new Vue({
			el: '#app',
			data: {
			}
		})
	</script>
</html>

複製程式碼

v-for 中key 的必要性,指定後表明 當前操作的項唯一

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script src="../lib/vue.js"></script>
	</head>
	<body>
		<div id="app">	
			<!-- v-for中 key屬性只能使用 number或者string 型別 -->
			<!-- v-for中key 必須使用v-bind 的屬性繫結形式,指定key的值  -->
			<p v-for="(item,index) in list" :key="item.id">id:{{item.id}}===name:{{item.name}} ===索引:{{index}}</p>
		</div>
	</body>
	<script>
		var app = new Vue({
			el: '#app',
			data: {
				list:[
					{id:1,name:'lij1'},
					{id:2,name:'lij2'},
					{id:3,name:'lij3'},
					{id:4,name:'lij4'},
				]
			}
		})
	</script>
</html>
複製程式碼

總結

v-for 指令 in後面的可迭代的 型別有

  1. 普通陣列
  2. 物件陣列
  3. 物件
  4. 數字

相關文章