循环使用 v-for 指令。
v-for 指令需要以 site in sites 形式的特殊语法, sites 是源数据数组并且 site 是数组元素迭代的别名。
v-for 可以绑定数据到数组来渲染一个列表:
<div id="app">
<ol>
<li v-for="site in sites">
{{ site.text }}
</li>
</ol>
</div>
<script>
const app = {
data() {
return {
sites: [
{ text: 'Google' },
{ text: 'Runoob' },
{ text: 'Taobao' }
]
}
}
}
Vue.createApp(app).mount('#app')
</script>
v-for 还支持一个可选的第二个参数,参数值为当前项的索引:
index 为列表项的索引值:
<div id="app">
<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' }
]
}
}
}
Vue.createApp(app).mount('#app')
</script>
模板 <template> 中使用 v-for:
<ul>
<template v-for="site in sites">
<li>{{ site.name }}</li>
<li>--------------</li>
</template>
</ul>
v-for 可以通过一个对象的属性来迭代数据:
<div id="app">
<ul>
<li v-for="value in object">
{{ value }}
</li>
</ul>
</div>
<script>
const app = {
data() {
return {
object: {
name: '菜鸟教程',
url: 'http://www.runoob.com',
slogan: '学的不仅是技术,更是梦想!'
}
}
}
}
Vue.createApp(app).mount('#app')
</script>
如果你还没了解组件的内容,可以先跳过这部分。
在自定义组件上,你可以像在任何普通元素上一样使用 v-for:
<my-component v-for="item in items" :key="item.id"></my-component>
然而,任何数据都不会被自动传递到组件里,因为组件有自己独立的作用域。为了把迭代数据传递到组件里,我们要使用 props:
<my-component
v-for="(item, index) in items"
:item="item"
:index="index"
:key="item.id"
></my-component>
不自动将 item 注入到组件里的原因是,这会使得组件与 v-for 的运作紧密耦合。明确组件数据的来源能够使组件在其他场合重复使用。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。