Get the App
SLTechnology News&Howtos  ›  Development  › 

What are the reasons why index is not recommended for key in Vue

Shulou Source: shulou.com Published: 2022-06-02 09:39:50 09月30日 Update

This article mainly introduces the reasons why Vue does not recommend using index as key. It has certain reference value. Interested friends can refer to it. I hope you will gain a lot after reading this article. Let Xiaobian take you to understand it together.

In front-end development, as long as it involves list rendering, then both React and Vue frameworks will prompt or require each list item to use a unique key, and many developers will directly use the index of the array as the key value without knowing the principle of the key. Then this article explains what key does and why it is best not to use index as a key attribute value.

Role of Key

Vue uses virtual dom and compares the old DOM with the new DOM according to diff algorithm, so as to update the real dom. Key is the unique identifier of virtual DOM object. Key plays an extremely important role in diff algorithm.

Key's role in diff algorithm

In fact, the diff algorithm in React, Vue, is roughly the same, but the diff comparison method is still quite different, and even each version of diff is quite different. Below we take the Vue3.0 diff algorithm as the entry point to analyze the role of key in diff algorithm.

The specific diff process is as follows

In Vue 3.0, there is such a source code in the patchChildren method

if (patchFlag > 0) { if (patchFlag & PatchFlags.KEYED_FRAGMENT) { /* For diff algorithm if key exists */ patchKeyedChildren( ... ) return } else if (patchFlag & PatchFlags.UNKEYED_FRAGMENT) { /* If there is no key, patch */ patchUnkeyedChildren( ... ) return } }

patchChildren performs a real diff or a direct patch depending on whether a key exists. We will not delve into the case where key does not exist.

Let's look at some declared variables first.

/* c1 old vnode c2 new vnode */let i = 0 /* Record index */const l2 = c2.length /* Number of new vnodes */let e1 = c1.length - 1 /* Index of last node of old vnode */let e2 = l2 - 1 /* Index of the last node of the new node */Sync head node

The first thing to do is to start from scratch and find the same vnode, and then patch , and if it is not the same node, then immediately jump out of the loop.

//(a b) c//(a b) d e/* Find the same node patch from the beginning. If you find a difference, jump out immediately */ while (i

Tags: Node data situation sequence algorithm move input function order longest same that is add one array process article development example just numerical value Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Redmi Apple NVidia Shulou Tech Info Microsoft