0
0
Vueframework~5 mins

Key attribute and why it matters in Vue

Choose your learning style9 modes available
Introduction

The key attribute helps Vue track elements when lists change. It makes updates faster and avoids bugs.

When rendering a list of items with <code>v-for</code>.
When items in a list can be added, removed, or reordered.
When you want Vue to reuse elements correctly instead of recreating them.
When you want to keep input fields or components from losing focus or state during updates.
Syntax
Vue
<template>
  <ul>
    <li v-for="item in items" :key="item.id">{{ item.name }}</li>
  </ul>
</template>

The key must be unique for each item in the list.

Use a stable identifier like an ID, not the array index.

Examples
Using a unique id as the key for each user.
Vue
<template>
  <ul>
    <li v-for="user in users" :key="user.id">{{ user.name }}</li>
  </ul>
</template>
Using the index as key is not recommended because it can cause bugs when the list changes.
Vue
<template>
  <ul>
    <li v-for="(item, index) in items" :key="index">{{ item }}</li>
  </ul>
</template>
Sample Program

This component shows a list of fruits. Clicking the button shuffles the list. Using :key="item.id" helps Vue update the list efficiently without losing track of each fruit.

Vue
<template>
  <div>
    <button @click="shuffle">Shuffle List</button>
    <ul>
      <li v-for="item in items" :key="item.id">{{ item.name }}</li>
    </ul>
  </div>
</template>

<script setup>
import { ref } from 'vue'

const items = ref([
  { id: 1, name: 'Apple' },
  { id: 2, name: 'Banana' },
  { id: 3, name: 'Cherry' }
])

function shuffle() {
  items.value = [...items.value].sort(() => Math.random() - 0.5)
}
</script>
OutputSuccess
Important Notes

Always use a unique and stable key to avoid rendering bugs.

Keys help Vue know which elements changed, so it can update only those.

Using array index as key can cause problems when items are reordered or removed.

Summary

The key attribute is important for list rendering in Vue.

It must be unique and stable for each item.

Using keys improves performance and prevents bugs when lists change.