Vue之v-for基本用法(020)

Vue之v-for基本用法

1. 遍历基本数组
完整代码:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<script src="../js/vue.js"></script>
		<title>v-for</title>
	</head>
	<body>
		<div id="app">
			<ul>
				<li v-for="book of books">{{book}}</li>
				<!--遍历数组时建议用of-->
			</ul>
		</div>
		<script>
			let vm = new Vue({
				el: "#app",
				data: {
					books: ["《明茨伯格管理进行时》", "《你当像鸟飞往你的山》", "《香农传》", "《如何把产品打造成有生命的品牌》", "《金色梦乡》", "《推理要在本格前》", "《东言西语》",
						"《新零售:低价高效的数据赋能之路》", "《知的资本论:茑屋书店的经营之道》", "《重来:更为简单有效的商业思维》"
					]
				},
			})
		</script>
	</body>
</html>

效果如图:
在这里插入图片描述
在遍历数组时,同时得到index。更改代码为:

<li v-for="(book,index) of books">{{book}}的index为====={{index}}</li>

效果如图:
在这里插入图片描述
取出index对操作“当前”的对象很有用。

2. 遍历对象数组
完整代码

<html>
	<head>
		<meta charset="utf-8">
		<script src="../js/vue.js"></script>
		<title>v-for</title>
	</head>
	<body>
		<div id="app">
			<ul>
				<li v-for="book of books">书名:{{book.name}}  作者:{{book.author}}  价格:{{book.price}}</li>
				<!--遍历数组时建议用of-->
			</ul>
		</div>
		<script>
			let vm = new Vue({
				el: "#app",
				data: {
					books: [{
							name: "Spring Boot + Vue全栈开发实战",
							author: "王松",
							price: 58
						},
						{
							name: "深入浅出Vue.js",
							author: "刘博文",
							price: 62.4
						},
						{
							name:" Vue.js 前端开发 快速入门与专业应用",
							author: "陈陆洋",
							price: 21.6
						}
					]
				},
			})
		</script>
	</body>
</html>

效果如图:
在这里插入图片描述

3. 遍历对象属性
更改代码为:

	<table>
				<!--遍历数组时建议用of-->
				<tr v-for="book of books">
					<!--遍历对象属性时建议用of-->
					<td v-for="(value,key,index) in book">{{key}}:{{value}} 对象内index为:{{index}}</td>
				</tr>
			</table>

效果如图:
在这里插入图片描述
4. 遍历数字
完整代码:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<script src="../js/vue.js"></script>
		<title>v-for</title>
	</head>
	<body>
		<div id="app">
			<ul>
				<li v-for="num of 10">{{num}}</li>
			</ul>
		</div>
		<script>
			let vm = new Vue({
				el: "#app",
			})
		</script>
	</body>
</html>

效果如图:
在这里插入图片描述
总结:

  1. V-for循环遍历数组时推荐使用of,语法格式为 item of arry 或 (item,index) of arry。
  2. V-for循环遍历对象时推荐使用in,语法格式为 (value,key) in object 或 (value,key,index) of object。
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值