循环遍历
v-for 与 v-if一同使用
💣 不推荐在同一元素上使用
v-if和v-for。当它们处于同一节点,Vue3.x 中v-if的优先级比v-for更高。这意味着v-if将没有权限访问v-for里的变量。Vue2.x 中v-for会优先作用。
<!--报错 isComplete 访问不到-->
<p v-for="todo in todos" v-if="todo.isComplete">{{todo.do}}</p>
可以把 v-for 移动到 <template> 标签中来修正:
<template v-for="todo in todos">
<li v-if="todo.isComplete">
{{ todo.name }}
</li>
</template>
v-for 作用域
在 v-for 块中,我们可以访问所有父作用域的属性。v-for 还支持一个可选的第二个参数,即当前项的索引。
<ul id="example-2">
<li v-for="(item, index) in items">
{{ parentMessage }} - {{ index }} - {{ item.message }}
</li>
</ul>
new Vue({
data:{
parentMessage:'Parent',
items:[
{ message:'Foo' },
{ message:'Bar' }
]
}
})