Home  >  Article  >  Web Front-end  >  Let’s talk about the role of key in vue for loop

Let’s talk about the role of key in vue for loop

青灯夜游
青灯夜游forward
2022-10-13 19:50:251453browse

vue What is the role of key in the for loop? The following article will introduce to you the role of key in the vue for loop. I hope it will be helpful to you.

Let’s talk about the role of key in vue for loop

Title description:

Whether it is react or vue framework, each will be prompted or required when rendering the list List items use unique keys. What does this key do? How to set the value correctly?

Answer analysis:

This question actually tests the understanding of the diff algorithm in the virtual dom object. [Related recommendations: vuejs video tutorial]

The essence of the diff algorithm is to find the difference between the old and new virtual DOM objects, with the purpose of reusing nodes as much as possible and improving performance.

The main function of key is to determine whether the old and new nodes are of the same type in the diff algorithm, so as to reuse the old nodes corresponding to the new nodes and save performance overhead

export function isSameVNodeType(n1: VNode, n2: VNode): boolean {
  return n1.type === n2.type && n1.key === n2.key
}

Give a negative example Understand that we often use the index of the array as the key of the list. Let’s take a look at the specific process.

Let’s talk about the role of key in vue for loop

If elements are added sequentially, the order will not be messed up, so there will be no It can be used normally;

If there is list deletion or element swapping, because the key (index) is the same, the order of the new node and the order of the old node still correspond one-to-one from front to back. However, by judging the content of the node, the element content has actually changed and requires a content update, which causes a performance overhead. You can observe changes in node content in the chrome debugging tool. If you are interested, you can try it.

(Learning video sharing: web front-end development, Basic programming video)

The above is the detailed content of Let’s talk about the role of key in vue for loop. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:juejin.cn. If there is any infringement, please contact admin@php.cn delete