Demo地址
先准备这样一个vue对象:
<script>
var app = new Vue({
el:'#app',
data:{
names:['allen','marry','tom'],
person:
[{name:'allen1',age:27},
{name:'allen2',age:28},
{name:'allen3',age:29},
]
}
});
</script>
我们直接看下面的代码:
<lu>
<!--names是vue中的数组,name是自定义的变量-->
<li v-for="name in names">
{{name}}<!--拿到name就可以显示-->
</li>
</lu>
<!--template 可以省略一些不必要的dom元素-->
<template v-for="(user,index) in person">
<!--index是下标,user是person的元素,person是vue中的数组-->
{{index}}:{{user.name}}-{{user.age}}
</template>
<template v-for="user in person">
<p v-for="(value,key) in user">
value:{{value}} - key:{{key}}
</p>
</template>
代码说明:
-
v-for="name in names"
,这个names
代表的就是vue
对象中的数组names
,name
是我们自己定义的一个变量. -
v-for="(user,index) in person"
,其中person
是vue
对象中的数组person
,user
是person
中的对象元素,index
是对象元素的下标. -
"(value,key) in user"
,value
和key
是user
里面的value
和key
,通过这种方式可以拿到对应需要的value
或者key
-
template
可以帮我们省略一些不必要的dom元素,例如我一个块只用<span>
就可以解决问题的,但是我多套了一层<div>
,这个时候template
就可以帮我们省略掉这个<div>
了.