与模板v-if类似,您还可以使用带有 v-for 的< template >标签来呈现多个元素的块。
<ul>
<template v-for="item in items">
<li>{{ item.msg }}</li>
<li class="divider"></li>
</template>
</ul>
v-for 和 v-if
当 v-for 与 v-if 一起使用时,v-for 具有比 v-if 更高的优先级,这意味着 v-if 将分别重复运行于每个 v-for 循环中。当我们仅为某些项目渲染节点时,这可能很有用:
<li v-for="todo in todos" v-if="!todo.isComplete">
{{ todo }}
</li>而如果我们的目的是有条件地跳过循环的执行,那么可以将 v-if 置于外层元素 (或 < template >)上。如:
<ul v-if="todos.length">
<li v-for="todo in todos">
{{ todo }}
</li>
</ul>
<p v-else>No todos left!</p>组件的 v-for
在 Vue 的 2.2.0 以上的版本中,我们要在组件中使用 v-for 时,不许使用 key
<my-component v-for=”(item,index) in itmes” v-bind:key=”index”></my-component>
虽然在自定义组件里可以使用 v-for ,但是,他不能自动传递数据到组件里,因为组件有自己独立的作用域。为了传递迭代数据到组件里,我们要用 props :
<my-component v-for="(item,index) in items" v-bind:key="index" :lie="item.text"l></my-component><script>
Vue.component('mycom', {
template: "<p>{{this.lie}}</p>",
props:["lie"] })
var exp=new Vue({
el:".exp",
data:{
items:[
{text:'从前有座山'},
{text:'山上有座庙'},
{text:'庙里有个老和尚'},
{text:'正在玩王者荣耀'}
] }
})
</script>
结果
从前有座山
山上有座庙
庙里有个老和尚
正在玩王者荣耀










