Function of key in Vue Diff algorithm V-for

How do keys function in React Vue?

Functions of keys in the virtual DOM

Key is the identification of the virtual DOM object. When the data in the state changes,Vue will generate a new virtual DOM according to the new data, and then Vue compares the difference between the new virtual DOM and the old virtual DOM

Compare the rules

  1. The same key as the new virtual DOM is found in the old virtual DOM:

    • If the content of the virtual DOM does not change, use the real DOM directly
    • If the contents of the virtual DOM change, a new real DOM is generated that replaces the previous real DOM in the page
  2. The old virtual DOM does not have the same key as the new virtual DOM

    Creating a new real DOM is then rendered to the page

Using index as the key may cause problems

  1. If data is added in reverse order or deleted in reverse order, the sequence is broken.

    It produces an unnecessary real DOM update interface that is fine but inefficient

  2. If the structure also contains the input DOM class:

    There are problems with the DOM update interface

How to select keys in development

  1. It is best to use the unique identifier of each piece of data as the key, such as ID, mobile phone number, ID number, id number, etc
  2. If you don’t have to reverse the order of the data add reverse delete and so on to break the order only to render the list for display using index as the key is ok

Why do templates have a root tag

The comparison between the virtual DOM and the real DOM starts with the tag. If there are multiple tags, the virtual DOM cannot be compared

Diff algorithm disadvantages Why use key

Without a key, the virtual DOM is compared with the real DOM in order. If the third tag is deleted, the Diff algorithm will compare the third tag in the virtual DOM with the fourth tag in the previous real DOM, resulting in the change of all the doms behind the third dom The virtual DOM will assume that the real DOM has changed since the third one and if the last one doesn’t it will delete it and add a key to make it unique and the virtual DOM will compare the same key