Vue List Rendering
List rendering turns an array into repeated HTML on the page. Vue builds one row for each item in the array.
A list of words
One row appears for each fruit.
<li v-for="fruit in fruits">{{ fruit }}</li>A list of objects
Each row shows the name and the role.
<li v-for="person in people">{{ person.name }} is a {{ person.role }}</li>The array behind it
The array holds the words for the rows.
const fruits = ref(['Apple', 'Banana', 'Cherry'])Example
<script setup>
import { ref } from 'vue'
const fruits = ref(['Apple', 'Banana', 'Cherry'])
const people = ref([
{ name: 'Ada', role: 'Cook' },
{ name: 'Ben', role: 'Driver' }
])
</script>
<template>
<div>
<ul>
<li v-for="fruit in fruits">{{ fruit }}</li>
</ul>
<ul>
<li v-for="person in people">{{ person.name }} is a {{ person.role }}</li>
</ul>
</div>
</template>Key points
- v-for is a directive that repeats a tag once for each item in an array.
- The first word after v-for names one item, and the word after in names the array.
- The item name can be used inside the repeated tag, like {{ fruit }}.
- An array of objects works the same way, and each row shows one part.
- When the array changes, the page updates to match the new list.
In this example, fruits is a ref that holds three words. people is a ref that holds two objects. The first list repeats one row for each fruit. The second list repeats one row for each person. Each person row shows a name and a role. The page shows three fruit rows and two person rows.
Note
This lesson leaves out :key on purpose, and the next lesson adds it.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does v-for do with an array?