How to Use key in v-for Vue: Syntax and Best Practices
In Vue, use the
key attribute inside a v-for loop to give each item a unique identifier. This helps Vue track elements efficiently and update the DOM correctly when data changes. The key should be a unique value like an ID from your data.Syntax
The v-for directive loops over an array or object. The key attribute must be added to the element inside the loop to uniquely identify each item. This helps Vue optimize rendering.
item: current element in the loopindex: optional index of the elementkey: unique identifier for each element, usually a property ofitem
vue
<template>
<ul>
<li v-for="(item, index) in items" :key="item.id">
{{ index }} - {{ item.name }}
</li>
</ul>
</template>Example
This example shows a list of users rendered with v-for. Each li has a key set to the user's unique id. This ensures Vue updates only changed items efficiently.
vue
<template>
<div>
<h2>User List</h2>
<ul>
<li v-for="user in users" :key="user.id">
{{ user.name }} (ID: {{ user.id }})
</li>
</ul>
</div>
</template>
<script setup>
import { ref } from 'vue'
const users = ref([
{ id: 101, name: 'Alice' },
{ id: 102, name: 'Bob' },
{ id: 103, name: 'Carol' }
])
</script>Output
User List
- Alice (ID: 101)
- Bob (ID: 102)
- Carol (ID: 103)
Common Pitfalls
Common mistakes include:
- Using the array index as
key, which can cause rendering bugs when the list changes. - Not providing a
keyat all, which makes Vue warn and slows updates. - Using non-unique keys, which breaks Vue's tracking and causes unexpected UI behavior.
Always use a unique and stable value like an ID from your data.
vue
<template>
<!-- Wrong: Using index as key -->
<ul>
<li v-for="(item, index) in items" :key="index">
{{ item.name }}
</li>
</ul>
<!-- Right: Using unique id as key -->
<ul>
<li v-for="item in items" :key="item.id">
{{ item.name }}
</li>
</ul>
</template>Quick Reference
- Use
keywithv-forto help Vue track elements. - Always use a unique and stable value like an ID.
- Avoid using array index as
keyunless the list is static and never changes. - Missing or duplicate keys cause rendering issues and warnings.
Key Takeaways
Always add a unique
key attribute when using v-for in Vue.Use a stable unique identifier like an ID from your data as the
key.Avoid using the array index as
key to prevent rendering bugs.Missing or duplicate keys cause Vue to warn and slow down updates.
Proper keys help Vue update only changed elements efficiently.