We can use the v-for
directive to render a list of items based on an array. The v-for
directive requires a special syntax in the form of item in items
, where items
is the source data array and item
is an alias for the array element being iterated on:
<ul id="example-1">
<li v-for="item in items" :key="item.message">
{{ item.message }}
</li>
</ul>
var example1 = new Vue({
el: '#example-1',
data: {
items: [
{ message: 'Foo' },
{ message: 'Bar' }
]
}
})
Example 2 how to iterate object:
You can also use v-for
to iterate through the properties of an object.
<ul id="v-for-object" class="demo">
<li v-for="value in object">
{{ value }}
</li>
</ul>
new Vue({
el: '#v-for-object',
data: {
object: {
title: 'How to do lists in Vue',
author: 'Jane Doe',
publishedAt: '2016-04-10'
}
}
})
You can also provide a second argument for the property’s name (a.k.a. key):
<div v-for="(value, name) in object">
{{ name }}: {{ value }}
</div>
// the result is like this
title: How to do lists in Vue
author: Jane Doe
publishedAt: 2016-04-10
And another for the index:
<div v-for="(value, name, index) in object">
{{ index }}. {{ name }}: {{ value }}
</div>
// the result is like this
0. title: How to do lists in Vue
1. author: Jane Doe
2. publishedAt: 2016-04-10
Inside v-for
blocks we have full access to parent scope properties. v-for
also supports an optional second argument for the index of the current item.
<ul id="example-2">
<li v-for="(item, index) in items" :key="index">
{{ parentMessage }} - {{ index }} - {{ item.message }}
</li>
</ul>
var example2 = new Vue({
el: '#example-2',
data: {
parentMessage: 'Parent',
items: [
{ message: 'Foo' },
{ message: 'Bar' }
]
}
})
v-for
on a <template>
Similar to template v-if
, you can also use a <template>
tag with v-for
to render a block of multiple elements. For example:
<ul>
<template v-for="item in items">
<li>{{ item.msg }}</li>
<li class="divider" role="presentation"></li>
</template>
</ul>
Example how to use v-if with v-for:
<ul v-if="shouldShowUsers">
<li v-for="user in users" :key="user.id" > {{ user.name }} </li>
</ul>
Example how to use v-for with components:
<my-component v-for="item in items" :key="item.id"></my-component>