适用范围:
1. 可迭代对象有:
- 数组
- 对象
2. 可以使用该命令的标签种类:
- Vue组件
- html标签
梗概:
语法超级类似于js中的for of
1. 维护顺序以及改善性能:
child::Vue 维护渲染顺序以及改善性能
实例:
1. 遍历数组:
<ul id="array-with-index">
<li v-for="(item, index) of items">
{{ parentMessage }} - {{ index }} - {{ item.message }}
</li>
</ul>Vue.createApp({
data() {
return {
parentMessage: 'Parent',
items: [{ message: 'Foo' }, { message: 'Bar' }]
}
}
}).mount('#array-with-index')结果:
- Parent-0-foo
- Parent-1-Bar
2. 遍历对象:
<ul id="v-for-object">
<li v-for="(value, name, index) of myObject">
{{ index }}. {{ name }}: {{ value }}
</li>
</ul>Vue.createApp({
data() {
return {
myObject: {
title: 'How to do lists in Vue',
author: 'Jane Doe',
publishedAt: '2016-04-10'
}
}
}
}).mount('#v-for-object')结果:
- 0. title: How to do lists in Vue
-
- author: Jane Doe
-
- publishedAt: 2016-04-10