#### v-for
```html
```
```js
var example1 = new Vue({
el: '#example-1',
data: {
items: [
{ message: 'Foo' },
{ message: 'Bar' }
]
}
})
```
```html
-
{{ parentMessage }} - {{ index }} - {{ item.message }}
```
```js
var example2 = new Vue({
el: '#example-2',
data: {
parentMessage: 'Parent',
items: [
{ message: 'Foo' },
{ message: 'Bar' }
]
}
})
```
### v-for遍历一个对象的元素
```html
{{ name }}: {{ value }}
{{ index }}. {{ name }}: {{ value }}
```
```js
new Vue({
el: '#v-for-object',
data: {
object: {
title: 'How to do lists in Vue',
author: 'Jane Doe',
publishedAt: '2016-04-10'
}
}
})
```
#### 显示过滤/排序后的结果
- 有时,我们想要显示一个数组经过过滤或排序后的版本,而不实际变更或重置原始数据。在这种情况下,可以创建一个计算属性,来返回过滤或排序后的数组。
```html
{{ n }}
```
```js
data: {
numbers: [ 1, 2, 3, 4, 5 ]
},
computed: {
evenNumbers: function () {
return this.numbers.filter(function (number) {
return number % 2 === 0
})
}
}
```
- 在计算属性不适用的情况下 (例如,在嵌套 `v-for` 循环中) 可以使用一个方法
```html
```
```js
data: {
sets: [[ 1, 2, 3, 4, 5 ], [6, 7, 8, 9, 10]]
},
methods: {
even: function (numbers) {
return numbers.filter(function (number) {
return number % 2 === 0
})
}
}
```
```html
{{ n }}
```
#### v-for,v-if 一同使用
- 当它们处于同一节点,`v-for` 的优先级比 `v-if` 更高,这意味着 `v-if` 将分别重复运行于每个 `v-for` 循环中。当你只想为*部分*项渲染节点时,这种优先级的机制会十分有用。
-
```html
<--代码将只渲染未完成的 todo-->
{{ todo }}
No todos left!
```
#### v-for在组件中
```html
```
```js
Vue.component('todo-item', {
template: '\
\
{{ title }}\
\
\
',
props: ['title']
})
new Vue({
el: '#todo-list-example',
data: {
newTodoText: '',
todos: [
{
id: 1,
title: 'Do the dishes',
},
{
id: 2,
title: 'Take out the trash',
},
{
id: 3,
title: 'Mow the lawn'
}
],
nextTodoId: 4
},
methods: {
addNewTodo: function () {
this.todos.push({
id: this.nextTodoId++,
title: this.newTodoText
})
this.newTodoText = ''
}
}
})
```