When Vue is updating a list of elements rendered with v-for
, by default it uses an “in-place patch” strategy. If the order of the data items has changed, instead of moving the DOM elements to match the order of the items, Vue will patch each element in-place and make sure it reflects what should be rendered at that particular index. This is similar to the behavior of track-by="$index"
in Vue 1.x.
This default mode is efficient, but only suitable when your list render output does not rely on child component state or temporary DOM state (e.g. form input values).
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:
<div v-for="item in items" v-bind:key="item.id">
<!-- content -->
</div>
It is recommended to provide a key
attribute with v-for
whenever possible, unless the iterated DOM content is simple, or you are intentionally relying on the default behavior for performance gains.
Since it’s a generic mechanism for Vue to identify nodes, the key
also has other uses that are not specifically tied to v-for
, as we will see later in the guide.
Don’t use non-primitive values like objects and arrays as v-for
keys. Use string or numeric values instead.
For detailed usage of the key
attribute, please see the key
API documentation.