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

← All Vue.js Developer questions