Performance: Key attribute and why it matters
This affects how Vue efficiently updates the DOM during re-rendering, impacting interaction responsiveness and visual stability.
<template>
<ul>
<li v-for="item in items" :key="item.id"> {{ item.name }} </li>
</ul>
</template><template>
<ul>
<li v-for="(item, index) in items" :key="index"> {{ item.name }} </li>
</ul>
</template>| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Using index as key | Many node removals and insertions | Multiple reflows per update | High paint cost due to layout shifts | [X] Bad |
| Using unique id as key | Minimal node updates | Single reflow per update | Low paint cost, stable layout | [OK] Good |
key attribute important when rendering lists in Vue?key attribute to identify each item uniquely when rendering lists.keykey attribute in a Vue v-for loop?key attribute should be bound with : to a unique and stable value, like item.id.<li v-for="item in items" :key="item.id">{{ item.name }}</li> uses :key="item.id", which is correct and stable for each item.items array changes?<template>
<ul>
<li v-for="item in items" :key="item.id">{{ item.name }}</li>
</ul>
</template>
<script setup>
import { ref } from 'vue'
const items = ref([
{ id: 1, name: 'Apple' },
{ id: 2, name: 'Banana' },
{ id: 3, name: 'Cherry' }
])
// Later update
items.value = [
{ id: 2, name: 'Banana' },
{ id: 3, name: 'Cherry' },
{ id: 4, name: 'Date' }
]
</script>key attribute to match existing DOM elements with new data by id.<ul>
<li v-for="(item, index) in items" :key="index">{{ item.name }}</li>
</ul>items can be reordered or changed dynamically.key is unstable when the list changes order or items are added/removed.v-for. Which key choice is best to avoid rendering bugs and improve performance?Pass the test and this pattern moves unknown