The v-for directive in Vue lets you repeat elements for each item in a list. Using an index helps you know the position of each item while looping.
0
0
v-for with index in Vue
Introduction
When showing a list of tasks and you want to number them.
When displaying a list of names and you want to highlight the first or last item.
When you need to track the position of items for styling or logic.
When creating a table and you want to show row numbers.
When you want to add unique keys using the index for better rendering.
Syntax
Vue
<template> <div v-for="(item, index) in items" :key="index"> {{ index }} - {{ item }} </div> </template>
The v-for directive takes two arguments inside parentheses: the item and its index.
Always use :key with a unique value like the index to help Vue track elements efficiently.
Examples
Loops over
fruits array and shows each fruit with its index.Vue
<div v-for="(fruit, i) in fruits" :key="i"> {{ i }}: {{ fruit }} </div>
Loops over
users array, shows user names with 1-based numbering, and uses user ID as key.Vue
<li v-for="(user, idx) in users" :key="user.id"> {{ idx + 1 }}. {{ user.name }} </li>
Sample Program
This example shows a list of colors with their indexes starting from 0.
Vue
<template>
<ul>
<li v-for="(color, index) in colors" :key="index">
{{ index }} - {{ color }}
</li>
</ul>
</template>
<script setup>
import { ref } from 'vue'
const colors = ref(['Red', 'Green', 'Blue'])
</script>OutputSuccess
Important Notes
Index starts at 0 by default.
Using the index as a key is okay for static lists but not recommended if the list changes order.
For dynamic lists, use a unique ID from the item as the key instead of the index.
Summary
v-for repeats elements for each item in a list.
You can get the index of each item by adding it in parentheses.
Use :key with a unique value to help Vue update the list efficiently.