Back
VueMediumNew
Why does Vue require a `:key` when using `v-for`?
Efficient DOM diffing / patch algorithm
Ideal Answer
The :key attribute gives Vue a stable identity for each item in a list, letting it accurately track, reuse, and reorder existing DOM elements during diffing instead of relying on index-based patching. Without a proper key (or using the array index as a key when items can be reordered/inserted/removed), Vue may reuse the wrong DOM nodes, causing stale state in inputs, transitions, or component instances.
JavaScript
<li v-for="item in items" :key="item.id">{{ item.name }}</li>
Always use a stable, unique identifier (like a database ID) rather than the array index whenever the list can change order.