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>
效果如图:
总结:
- V-for循环遍历数组时推荐使用of,语法格式为 item of arry 或 (item,index) of arry。
- V-for循环遍历对象时推荐使用in,语法格式为 (value,key) in object 或 (value,key,index) of object。