The v-for Directive
The v-for directive repeats an element once for each item in a list. Vue makes one copy of the element for each item.
Repeat a list item
The list holds Apple, Banana, and Cherry.
<li v-for="fruit in fruits">{{ fruit }}</li>Show the position too
The list holds Apple, Banana, and Cherry.
<li v-for="(fruit, index) in fruits">{{ index }}: {{ fruit }}</li>Repeat over objects
Each user has a name.
<li v-for="user in users">{{ user.name }}</li>An empty list shows nothing
The list holds no items.
<li v-for="fruit in empty">{{ fruit }}</li>Example
<script setup>
import { ref } from 'vue'
const fruits = ref(['Apple', 'Banana', 'Cherry'])
const users = ref([{ name: 'Ana' }, { name: 'Ben' }])
const empty = ref([])
</script>
<template>
<ul>
<li v-for="fruit in fruits">{{ fruit }}</li>
</ul>
</template>
Key points
- Write v-for with an item name and a list, like v-for="fruit in fruits".
- The item name stands for one item at a time.
- Use the item name inside the element, like {{ fruit }}.
- The list can hold strings or objects.
- v-for can also give the position of each item, like (fruit, index) in fruits.
In this example, the script makes a fruits list with three names. It also makes a users list with two names and an empty list. The template repeats one li for each fruit. The page first shows Apple, Banana, and Cherry. A list with two names shows two items instead.
Note
An empty list shows nothing.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does v-for do?