Demo地址
先準(zhǔn)備這樣一個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中的數(shù)組,name是自定義的變量-->
<li v-for="name in names">
{{name}}<!--拿到name就可以顯示-->
</li>
</lu>
<!--template 可以省略一些不必要的dom元素-->
<template v-for="(user,index) in person">
<!--index是下標(biāo),user是person的元素,person是vue中的數(shù)組-->
{{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對象中的數(shù)組names,name是我們自己定義的一個變量. -
v-for="(user,index) in person",其中person是vue對象中的數(shù)組person,user是person中的對象元素,index是對象元素的下標(biāo). -
"(value,key) in user",value和key是user里面的value和key,通過這種方式可以拿到對應(yīng)需要的value或者key -
template可以幫我們省略一些不必要的dom元素,例如我一個塊只用<span>就可以解決問題的,但是我多套了一層<div>,這個時候template就可以幫我們省略掉這個<div>了.