Vue v-for Tutorial
The v-for
directive is the right way to do list rendering in Vue. If your Vue instance has an array in data
, you can
render each element in the array using v-for
:
const app = new Vue({
data: () => ({ people: ['Axl Rose', 'Slash', 'Izzy Stradlin'] }),
// 1 `<li>` for each person in `people`
template: `
<div>
<h1>Band Members</h1>
<ul>
<li v-for="person in people">
{{person}}
</li>
</ul>
</div>
`
});
Vue also handles array change detection.
If you were to remove an element from the array using splice()
, Vue would remove an <li>
from the DOM for you.
// Remove "Izzy Stradlin" from the array, and also from the `<ul>`
this.array.splice(2, 1);
With v-model
Although you can loop over an array of strings using v-for
,
it won't work with v-model
. The v-model
directive won't
be able to update your array with any changes to the <input>
.
const app = new Vue({
data: () => ({ people: ['Axl Rose', 'Slash', 'Izzy Stradlin'] }),
// 1 `<input>` for each person in `people`
template: `
<div>
<h1>Band Members</h1>
<div id="people-array">{{people}}</div>
<ul>
<li v-for="person in people">
<input v-model="person">
<span>{{person}}</span>
</li>
</ul>
</div>
`
});
The way to work around this is to use an array of objects with v-for
.
Whenever you use v-model
with v-for
, make sure the property you're
binding with v-model
is an object property.
const app = new Vue({
data: () => ({
people: [
{ name: 'Axl Rose' },
{ name: 'Slash' },
{ name: 'Izzy Stradlin' }
]
}),
template: `
<div>
<h1>Band Members</h1>
<div id="people-array">{{people}}</div>
<ul>
<li v-for="person in people">
<input v-model="person.name">
<span>{{person.name}}</span>
</li>
</ul>
</div>
`
});
With Objects
You can also use v-for
to loop over the keys of an object using the v-for="(value, key) in obj"
syntax.
Note that v-for
only loops over own properties.
const app = new Vue({
data: () => ({
people: {
singer: 'Axl Rose',
guitarist: 'Slash',
bassist: 'Duff McKagan'
}
}),
// 3 `<li>` elements: "Axl Rose - singer", "Slash - guitarist",
// and "Duff McKagan - bassist"
template: `
<div>
<h1>Band Members</h1>
<ul>
<li v-for="(value, key) in people">
{{value}} - {{key}}
</li>
</ul>
</div>
`
});