Moment For Technology

Do not use index as key in Vue

Posted on Aug. 6, 2022, 1:49 a.m. by 王佩君
Category: The front end Tag: vue.js

Briefly answer

  1. 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.

  2. Use a component's unique ID (typically returned by the back end) as its key, and in the absence of one, a key can be created for the list as it is retrieved by some rule, and this key is guaranteed to remain stable throughout the life of the component.

  3. Using index as the key, no matter how you reverse the order of the array, index is 0, 1, 2, so Vue will reuse the wrong old child nodes, doing a lot of extra work, right

  4. Do not use random numbers as keys, otherwise old nodes will be deleted and new nodes will be created

Article reference: juejin.cn/post/684490...

Search
About
mo4tech.com (Moment For Technology) is a global community with thousands techies from across the global hang out!Passionate technologists, be it gadget freaks, tech enthusiasts, coders, technopreneurs, or CIOs, you would find them all here.