3 min read
•Question 22 of 37easyWhy 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
- Must be unique among siblings
- Don't use index for mutable lists
- Use primitive values (string/number)