What does key do?

Key is the unique ID given to each Vnode. You can rely on the key to get the corresponding VNode in oldVnode more accurately and faster.

You can refer to the sameVnode source code.

Use the unique ID as the key recommended by the official website. Because index as a key has the same effect as no key. When index is used as the key, the index of each list item is the same before and after the change. It is directly identified as sameVnode and reused.Copy the code

Ultimately, the key’s role is to determine whether two nodes are the same when updating a component. The same reuse, not the same to delete the old create a new.

Because you can't find reusable nodes for each update with a unique key, not only do you have to destroy and create vNodes, but adding and removing nodes to the DOM has a greater impact on performance. That's why they say "Performance may be better without keys." Render a 10W list item with a unique key versus no key:Copy the code

Case without key:

<li v-for="item in list">{{ item.text }}</li>
Copy the code

When id is used as key:

The list structure

 const list1 = []
  const list2 = []
  for (let i = 0; i <= 100000; i++) {
    list1.push({
      id: i,
      text: i
    })
    list2.push({
      id: i * 2,
      name: 100000 - i
    })
  };
Copy the code

Because points can be reused without keys, the overhead of destroying/creating components is eliminated, and you only need to modify the DOM text content rather than remove/add nodes, which is what the documentation calls “a deliberate reliance on default behavior for performance improvements.”

In that case, why do you recommend a key? Because this mode is only good for rendering simple stateless components. For most scenarios, the list component has its own state.

For example: a list of paging components, each item in the list contains images and text. Without the key attribute, when the first page and then switch to the second page, each item on the second page will still display the same image on the first page. You can add an ID as a unique key to the list item, so that every time the list is rendered, all components will be completely replaced to have the correct state.

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.