In-depth analysis of the key in vue to see what the key can be used for!
What is the use of key? The following article will give you an in-depth analysis of the key in vue to see what the key can be used for. I hope it will be helpful to everyone!
In-depth analysis of key in vue
What is the use of key?
- Let’s look at the official explanation first:
- The key attribute is mainly used in vue's
virtual DOM algorithm (diff algorithm)
, and is not used when identifying new and old nodes when comparing themVNodes
-
key
, Vue will use an algorithm that minimizes dynamic elements and tries tomodify/reuse elements of the same type
in place as much as possible -
Use key
, it will rearrange the order of elements based on key changes, and will
remove/destroy elements that have a key
that do not exist
- The key attribute is mainly used in vue's
Faced with these vague concepts, don’t be impatient. Read it once and get an impression. Next, we will analyze in depth step by step what the key is used for. [Related recommendations: "vue.js Tutorial"]
1 vnode virtual node
##vnode: virtual node, virtual node
Document, element, node
Simply put, the node to be rendered by vue on the page is a virtual node
<template id="my-app"> <div class="title" style="font-size: 30px; color: red;">哈哈哈</div> </template>The div here is a virtual node. In vue, it exists in this form
const vnode = { type: "div", props: { class: "title", style: { "font-size": "30px", color: "red", }, }, children: "哈哈哈", };What I don’t understand may be the children attribute, because now the div has no child elements, so the value is only "hahaha". If there are child elements, then it will be nested in a matryoshka until the last node. , such as
children: [ { // 子元素 }, { // 子元素 } ],
2 vDOM Virtual DOM
is the same as real DOM. If there are real nodes, there will be real DOM. Then if there are virtual nodes, then There is a virtual DOM Of course, the same goes for a virtual DOM tree. There is also a VNode tree, which means there is no need to worry about it. It is probably as follows<template id="my-app"> <div> <div> <p></p> <p></p> <ul> <li></li> <li></li> <li></li> </ul> </div> </div> </template>Convert to a virtual DOM tree:
When the virtual DOM is rendered into the real DOM, it is not necessarily exactly the same. This involves components, which I will talk about later when I have the opportunity
3 Rendering process
##4 Case: Insert fAfter understanding the previous ones, let’s get down to business. Only one case is needed to fully understand the role of key. Let’s start with
Let’s look at this simple case (without adding key)
<ul> <li v-for="item in letters">{{item}}</li> </ul>
data() { return { letters: ['a', 'b', 'c', 'd'] } }, methods: { insertF() { this.letters.splice(2, 0, 'f'); } },
It can be seen that the purpose of this question is to insert an f
between ab and cd. After understanding this simple case, we started to think about whether there is any way to insert it into the real DOM. What?
There are three following types:
Method one (ordinary method)
Instructions: Directly Delete the previous dom and re-render it with the new vnode
Note: This is vue's default diff algorithm when there is no key. The corresponding source code is as shown in the figure.
Vue will judge whether you have brought the key through the judgment statement
The following is the situation when there is no key
Then check
, you can view the execution process of the diff algorithmHere is a brief description:
- Get the old vnode and the new vnode
- Determine which of the two arrays has the smaller length (use the smaller one Patching a larger array will not cause the array to go out of bounds)
- Start patching, as mentioned in the picture, and continue patching until there is no space (at c of the new vnode) , divided into two situations
-
- old vnode
When old vnode > new vnode, uninstall the old vnode node
Similarly, you can view it by following the steps of method twopatchKeyedChildren()
This method is the essence, it starts to get complicated
-
Patch from the tail, when it is found to be different (here c !== f), break
So far, a, b, c, d have is rendered into the real DOM, the only difference is f, let’s start looking for f
-
to judge:
If the old vnode
If new vnode > old vnode, uninstall the redundant nodes of the old vnode
If new vnode = old vnode, this is very complicated. Regardless of the order, try to patch the same items in it, and then perform uninstall and mount operations
Summary: At this point, the entire case process has been completely gone through. The author can only understand this. This article combines coderwhy’s video and some of my own thoughts (video source: https://ke.qq.com/course /3453141), so there may be something wrong, everyone is welcome to criticize and correct me
[Related recommendations: "vue.js tutorial"]
The above is the detailed content of In-depth analysis of the key in vue to see what the key can be used for!. For more information, please follow other related articles on the PHP Chinese website!

Vue.js and React each have their own advantages in scalability and maintainability. 1) Vue.js is easy to use and is suitable for small projects. The Composition API improves the maintainability of large projects. 2) React is suitable for large and complex projects, with Hooks and virtual DOM improving performance and maintainability, but the learning curve is steeper.

The future trends and forecasts of Vue.js and React are: 1) Vue.js will be widely used in enterprise-level applications and have made breakthroughs in server-side rendering and static site generation; 2) React will innovate in server components and data acquisition, and further optimize the concurrency model.

Netflix's front-end technology stack is mainly based on React and Redux. 1.React is used to build high-performance single-page applications, and improves code reusability and maintenance through component development. 2. Redux is used for state management to ensure that state changes are predictable and traceable. 3. The toolchain includes Webpack, Babel, Jest and Enzyme to ensure code quality and performance. 4. Performance optimization is achieved through code segmentation, lazy loading and server-side rendering to improve user experience.

Vue.js is a progressive framework suitable for building highly interactive user interfaces. Its core functions include responsive systems, component development and routing management. 1) The responsive system realizes data monitoring through Object.defineProperty or Proxy, and automatically updates the interface. 2) Component development allows the interface to be split into reusable modules. 3) VueRouter supports single-page applications to improve user experience.

The main disadvantages of Vue.js include: 1. The ecosystem is relatively new, and third-party libraries and tools are not as rich as other frameworks; 2. The learning curve becomes steep in complex functions; 3. Community support and resources are not as extensive as React and Angular; 4. Performance problems may be encountered in large applications; 5. Version upgrades and compatibility challenges are greater.

Netflix uses React as its front-end framework. 1.React's component development and virtual DOM mechanism improve performance and development efficiency. 2. Use Webpack and Babel to optimize code construction and deployment. 3. Use code segmentation, server-side rendering and caching strategies for performance optimization.

Reasons for Vue.js' popularity include simplicity and easy learning, flexibility and high performance. 1) Its progressive framework design is suitable for beginners to learn step by step. 2) Component-based development improves code maintainability and team collaboration efficiency. 3) Responsive systems and virtual DOM improve rendering performance.

Vue.js is easier to use and has a smooth learning curve, which is suitable for beginners; React has a steeper learning curve, but has strong flexibility, which is suitable for experienced developers. 1.Vue.js is easy to get started with through simple data binding and progressive design. 2.React requires understanding of virtual DOM and JSX, but provides higher flexibility and performance advantages.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Dreamweaver Mac version
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.
