From the Vue docs (emphasis mine): https://vuejs.org/guide/essentials/list.html#maintaining-state-with-key
To give Vue a hint so that it can track each node's identity, and thus reuse and reorder existing elements, you need to provide a unique key attribute for each item
If the index of any item in the array is changed (e.g. by adding/removing a new item anywhere other than the end of the array), then Vue will lose track of the item.
For example:
let data = [A, B, C, D]
<div v-for="(item, index) in data" :key="index">
Vue tracks each item like this:
A: 0
B: 1
C: 2
D: 3
If you remove B
from the array, Vue will then track each item like this:
A: 0
C: 1
D: 2
The indices of C
and D
have changed, so Vue has lost track of them, and will remove D
from the rendered output instead of B
(because from its point of view, it is the item with index 3 that was removed).
This is why the key should uniquely identify an item, which an index does not do.
However, it also means that there are some cases where using the index as the key is acceptable:
- The array will not change
- Or the array will only have items added/removed at the end and will not be reordered
- Or the items are all identical
If you cannot use the index as a the key, but cannot uniquely identify items (e.g. some of the items in the list are identical), a solution may be to use lodash's uniqueId()
:
<div v-for="item in data" :key="uniqueId()">
or as mentioned here something like
<div v-for="(item, index) in data" :key="`${item.someProperty}-${index}`">