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后面的可迭代的 类型有
- 普通数组
- 对象数组
- 对象
- 数字