Vue v-for循环的用法
1、v-for循环普通数组
①创建Vue对象
<script>
var app = new Vue({
el:'#app',
data:{
array:[1,2,3,4,5,6,7,8],
}
})
</script>
②循环数组
<div id="app">
<p v-for="(item,index) of array">索引:{{index}}-数值:{{item}}</p>
</div>
显示结果:
2、v-for循环对象数组
①创建Vue对象
var app = new Vue({
el:'#app',
data:{
array2:[
{id:1,name:'刘亦菲',age:20},
{id:2,name:'刘诗诗',age:25},
{id:3,name:'张韶涵',age:30},
{id:4,name:'铁憨憨',age:35}
]
})
② 循环对象数组
<div id="app">
<p v-for="(item,index) of array2">索引:{{index}}-数据:{{item}}</p>
</div>
显示结果:
<div id="app">
<p v-for="(item,index) of array2">索引:{{index}}-数据:{{item.age}}</p>
</div>
3、v-for循环对象
①创建vue对象实例
<script>
var app = new Vue({
el:'#app',
data:{
list3:{
id:1,name:'刘诗诗',age:20
}
},
})
</script>
②循环对象
<div id="app">
<p v-for="(val,key,i) of list3">值:{{val}}-键值:{{key}}-索引:{{i}}</p>
</div>
4、v-for循环数字
<div id="app">
<p v-for="count in 5">这是第{{count}}循环</p>
</div>
5、v-for中key的使用方式
①创建vue对象实例
<script>
var app = new Vue({
el:'#app',
data:{
input:'',
input2:'',
input3:'',
array2:[
{id:1,name:'刘亦菲',age:20},
{id:2,name:'刘诗诗',age:25},
{id:3,name:'张韶涵',age:30},
{id:4,name:'铁憨憨',age:35}
],
},
methods:{
add(){
this.array2.push({id: this.input,name: this.input2,age: this.input3})
this.input = ''
this.input2 = ''
this.input3 = ''
}
},
})
</script>
②循环
注意:
- v-for循环的时候,key属性只能使用number或String。
- key在使用的时候,必须使用v-bind属性绑定的形式,指定key的值。
- 在组件中使用v-for循环的时候,或者在一些特殊情况中,如果v-for有问题,必须在使用v-for的同时,指定唯一的 字符串/数字 类型 :key值。
<div id="app">
<p v-for="item in array2" :key="item.id">{{item.id}}-{{item.name}}</p>
编号:<input type="number" v-model="input">
姓名:<input type="text" v-model="input2">
年龄:<input type="number" v-model="input3">
<input type="button" value="添加" @click="add">
</div>