#1 Data Analytics Program in India
₹2,499₹1,499Enroll Now
3 min read
Question 22 of 37easy

Why is the key attribute important in Vue?

Understanding key for list rendering.

What You'll Learn

  • Why key matters
  • Key in v-for
  • Key for forcing re-renders

Key in v-for

code.txtVUE
<!-- Always use unique key -->
<template>
  <li v-for="item in items" :key="item.id">
    {{ item.name }}
  </li>
</template>

Why Key Matters

Without key, Vue uses "in-place patch" strategy which can cause issues:

code.txtVUE
<!-- Bad: using index as key -->
<li v-for="(item, index) in items" :key="index">
  <input v-model="item.name">
</li>

<!-- Good: using unique id -->
<li v-for="item in items" :key="item.id">
  <input v-model="item.name">
</li>

Force Re-render with Key

code.txtVUE
<template>
  <!-- Component re-creates when userId changes -->
  <UserProfile :key="userId" :user-id="userId" />
</template>

Key Rules

  1. Must be unique among siblings
  2. Don't use index for mutable lists
  3. Use primitive values (string/number)