循环使用 v-for 指令。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/22224.html
v-for 指令需要以 site in sites 形式的特殊语法, sites 是源数据数组并且 site 是数组元素迭代的别名。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/22224.html
v-for 可以绑定数据到数组来渲染一个列表:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/22224.html
v-for 实例
<ol>
<li v-for="site in sites">
{{ site.text }}
</li>
</ol>
</div>
<script>
const app = {
data() {
return {
sites: [
{ text: 'Google' },
{ text: 'Runoob' },
{ text: 'Taobao' }
]
}
}
}文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/22224.html
Vue.createApp(app).mount('#app')
</script>文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/22224.html
v-for 还支持一个可选的第二个参数,参数值为当前项的索引:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/22224.html
v-for 实例
index 为列表项的索引值:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/22224.html
<ol>
<li v-for="(site, index) in sites">
{{ index }} -{{ site.text }}
</li>
</ol>
</div>
<script>
const app = {
data() {
return {
sites: [
{ text: 'Google' },
{ text: 'Runoob' },
{ text: 'Taobao' }
]
}
}
}文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/22224.html
Vue.createApp(app).mount('#app')
</script>文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/22224.html
模板 <template> 中使用 v-for:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/22224.html
v-for
v-for 迭代对象
v-for 可以通过一个对象的属性来迭代数据:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/22224.html
v-for
你也可以提供第二个的参数为键名:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/22224.html
v-for
第三个参数为索引:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/22224.html
v-for
v-for 迭代整数
v-for 也可以循环整数文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/22224.html
v-for
显示过滤/排序后的结果
我们可以对数组的元素进行处理后再显示出来,一般可以通过创建一个计算属性,来返回过滤或排序后的数组。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/22224.html
v-for 实例
输出数组中的偶数:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/22224.html
v-for/v-if 联合使用
以上实例联合使用 v-for/v-if 给 select 设置默认值:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/22224.html
v-for/v-if 实例
v-for 循环出列表,v-if 设置选中值:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/22224.html
在组件上使用 v-for
如果你还没了解组件的内容,可以先跳过这部分。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/22224.html
在自定义组件上,你可以像在任何普通元素上一样使用 v-for:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/22224.html
<my-component v-for="item in items" :key="item.id"></my-component>
然而,任何数据都不会被自动传递到组件里,因为组件有自己独立的作用域。为了把迭代数据传递到组件里,我们要使用 props:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/22224.html
<my-component v-for="(item, index) in items" :item="item" :index="index" :key="item.id" ></my-component>
不自动将 item 注入到组件里的原因是,这会使得组件与 v-for 的运作紧密耦合。明确组件数据的来源能够使组件在其他场合重复使用。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/22224.html
下面是一个简单的 todo 列表的完整例子:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/22224.html