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

本文详细介绍了Vue.js框架中v-for指令的四种使用方式,包括遍历普通数组、对象数组、对象以及数字。同时强调了在v-for循环中指定key的重要性,确保每一项的唯一性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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. 数字

转载于:https://juejin.im/post/5c7e934a6fb9a04a027b1ad9

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值