The v-for directive is used for rendering lists. It is able to take multiple arguments, and can be used in child or parent components.
- Template Syntax
<div v-for="item in :key="item.id">
<!-- content -->items"
</div>
- Script Syntax
data() {
return {
items: [
'item-1', 'item-2', 'item-3'
]
}
}
- The items can also be objects, you will be able to access all of the object's properties
- If you are passing data to a components props, you will need to bind the syntax so the loop knows how to assign the information
- This is very easy, all you need to do is add
:propVariable="dataVariableto the loop or component
<Component v-for="item in items" :key"item.id" :propVariable="dataVariable" /> - This is very easy, all you need to do is add
- You can use this on any html tag, it will create multiple of itself with the exact layout specified -If the data that is being looped is in the same file as the loop, you do not need to bind the values to it
- It is best to use a key
- adding
.idwill make the iterating item work as a key
- adding
- The key attribute is used for more than just looping. You can find extra readings here
There is more that the v-for can do.
v-forcan take multiple arguments to provide more variables to work with
indexcan be passed to add a counter, this can be really helpful for getting list numbers.- Remember that it starts counting at 0
<li v-for="(item, index) in items" :key="item.id">
{{ index + 1 }} - {{ item.value }}
</li>
- In this case, the output would be something like:
1 - Frodo
2 - Sam
3 - Pippin
namecan be passed to gain access to the property titles in an object
- This example uses all three arguments
- Template Syntax
<div v-for="(item, name, index) in object">
{{index.}} - {{ name }} - {{ item.species }} - {{ item.characterName }}
</div>
- Output will be something like
0 - Species - Hobbit - Frodo
1 - Species - Elf - Anwyn
2 - Species - Orc - Azog the Defiler
- This is for displaying a subset of a list of information
- It takes advantage of the
computedproperty - Read the Docs
- Template
<li v-for="char in hobbits" :key="char.id"> {{ char.name }}</li>
- Script
data() {
return {
characters:
{
name: 'Aragon',
species: 'Human'
},
{
name: 'Frodo',
species: 'Hobbit',
},
{
name: Anwyn,
species: 'Elf'
},
{
name: 'Pippin',
species: 'Hobbit'
}
}
},
computed: {
hobbits: function () {
return this.characters.filter((character) {
return character.species === "Hobbit"
})
}
}
- Output
- Frodo
- Pippin