Vue.js Developer interview question · Most asked
Why does v-for need a key, and why should it not be the index?
Summary
The key lets Vue match list items to existing DOM elements and component instances when the list changes, so it can move them instead of patching in place. A stable unique ID keeps each item's state (inputs, focus, component state, transitions) attached to the right data; the array index changes when items are inserted, removed or reordered, so state ends up on the wrong item.
Longer Answer
Without keys (or with index keys), Vue reuses elements by position. Deleting the first item of a list of inputs then shows the typed text shifted onto the wrong rows. Index keys are only safe for static lists that never reorder and have no per-item state. Keys must be unique among siblings and be strings or numbers.
Key Points
- Keys identify items across renders.
- Use a stable unique ID.
- Index keys misplace state on reorder.
- Required for transitions and component lists.
Deep dive: Code Clinic: review a Vue comment list
More most-asked Vue.js Developer questions
- Options API or Composition API: what is the difference, and which would you use?
- What are composables, and why did they replace mixins?
- How does Vue 3's reactivity system work, and how does it differ from Vue 2's?
- computed, watch or watchEffect: when do you use each?
- ref or reactive: what is the difference, and when do you use each?
- How do you use Vue Router: dynamic routes, nested routes and navigation guards?
- How do props work, and what is one-way data flow?
- Pinia or Vuex: what is the difference, and why is Pinia now recommended?