Question presented to candidate:
"Why does Vue want a :key on every v-for? What actually goes wrong if you leave it out or use the array index, and when is the index fine?"
What a strong answer should cover:
- Without a key, Vue patches list children in place by position (an "unkeyed" diff); with keys it matches old and new children by identity and moves, creates or removes them.
- Position matching is fine for plain text, but local state (component
refs, input values, focus, transitions) stays with the position, not the item, when the list is reordered or an item is removed. :key="index"is effectively the same as no key for reorders and removals.- Keys must be unique among siblings and stable across renders: database ids, not
Math.random()or new objects. - In Vue 3 the key on
<template v-for>goes on the<template>tag; duplicate keys produce a dev warning. - Changing a key on purpose forces a remount, a common reset technique.
Clarifying questions expected:
- "Do the list items have local state, such as inputs or child components?"
- "Can the list be reordered, filtered or have items removed from the middle?"
Code / implementation expected: Yes β a list of stateful rows rendered with index keys and id keys, showing state attached to the wrong item after a removal.