From vue source code

To make it easier to track the identity of each node and to reorder and reorder existing elements, add a key attribute to each entry

In the process of virtual DOM update to determine whether two VNodes are the same method

SameVnode is simple, but only if key, tag, isComment, and data are defined (or not) at the same time, and if the tag type is input, the type is the same. Some browsers do not support dynamic type modification. So they are considered different types).

Is it really fast with a key

In the example above, the contents of v-for generate the following ARRAY of DOM nodes, and we give each node an id:

Change dataList data, perform data location replacement, and compare the changed data

Add or delete dataList list items

From the above point of view, nodes can be reused more effectively without key and diff speed is also faster without key, because it takes time to add and delete nodes with key. This is what the VUE documentation calls the default mode. However, this is not the function of the key, but the node can be reused in the absence of a key to improve performance.

This mode has some hidden side effects, such as the possibility that transitions may not occur, or that there is bound data (form) state at some nodes and state mismatches occur. The VUE documentation also states that this default mode is efficient, but only for list rendering output that does not depend on child component state or temporary DOM state (for example, form input values)

The vUE website recommends providing key attributes whenever possible when using V-for, unless traversing the output DOM content is simple or you deliberately rely on default behavior for performance gains.

But what does key do?

  1. It’s more accurate because with a key it’s notIn situ reuseIn the sameNode functiona.key === b.keyIn – place reuse can be avoided in comparison. So it’s more accurate.
  2. Faster Using the uniqueness of keys to generate map objects to obtain corresponding nodes, faster than traversal. This is my original point of view. From this point of view, map is faster than traversal.)

conclusion

This is a simple example, but the practical application is more complicated. Wearing a unique key adds overhead, but the difference is almost invisible to the user and ensures that the component state is correct, which is why it is recommended to use a unique ID as the key. As to specific how to use, be about to choose according to actual situation.