How to use v-for with index in Vue
Accessing the index in v-for loops is essential for Vue applications that need to display item positions, apply conditional styling, or handle index-based operations. As the creator of CoreUI with over 11 years of Vue development experience since 2014, I’ve used indexed loops in countless data lists and tables. The most effective solution is to use the second parameter in v-for to access the index value. This approach provides access to both the item and its position in the array.
Use the index parameter in v-for to access item positions in Vue 3.
<template>
<div>
<h2>Simple Index Usage</h2>
<ul>
<li v-for='(item, index) in items' :key='item.id'>
{{ index + 1 }}. {{ item.name }}
</li>
</ul>
<h2>Conditional Styling with Index</h2>
<div
v-for='(item, index) in items'
:key='item.id'
:class='{ highlight: index % 2 === 0 }'
>
Row {{ index }}: {{ item.name }}
</div>
<h2>Index in Event Handlers</h2>
<button
v-for='(item, index) in items'
:key='item.id'
@click='handleClick(index, item)'
>
Select Item {{ index }}
</button>
</div>
</template>
<script>
import { ref } from 'vue'
export default {
setup() {
const items = ref([
{ id: 1, name: 'Item One' },
{ id: 2, name: 'Item Two' },
{ id: 3, name: 'Item Three' },
{ id: 4, name: 'Item Four' }
])
const handleClick = (index, item) => {
console.log(`Clicked item at index ${index}:`, item)
}
return { items, handleClick }
}
}
</script>
<style scoped>
.highlight {
background-color: #f0f0f0;
}
</style>
The v-for directive accepts a second parameter for the index, starting from 0. The syntax is (item, index) in array. Add 1 to display human-readable numbering starting from 1. Use the index for conditional styling with modulo operations for alternating rows. Pass the index to event handlers for position-based logic. Always use a unique :key prop, preferably from item data rather than the index.
Best Practice Note
This is the same index usage pattern we implement in CoreUI Vue components for numbered lists and tables. Avoid using index as the :key prop when the list order can change, as this can cause rendering issues. The index is useful for display but use stable unique IDs from your data for keys.



