Vue 3 key Attribute
key The key attribute is a critical special attribute of Vue's virtual DOM algorithm, mainly used to help Vue identify the uniqueness of each node, thereby efficiently updating the virtual DOM.
Basic Explanation
key attribute is used to provide a unique identifier for a Vue component or element. In list rendering, each v-for looped element should have a unique key attribute.
- Type: String | Number
- Purpose: Provides a unique identifier for each element in list rendering, helping Vue efficiently diff and reuse DOM nodes.
How It Works
When Vue performs virtual DOM diffing, without a key , Vue uses an algorithm that minimizes element movement and reuses elements of the same type in place as much as possible. With a key , Vue reorders elements based on changes in key order and removes elements whose keys no longer exist.
Child elements of the same parent must have unique keys. Duplicate keys cause rendering errors.
Basic Usage
The most common usage is combined with v-for to use:
Example
-
{{ item.name }}
Use Cases
1. List Rendering
in v-for Using it in key is the most common scenario:
Example
{{ user.id }}
{{ user.name }}
{{ user.email }}
2. Force Element Replacement
key can also be used to force the replacement of an element or component instead of reusing it. This is useful in the following scenarios:
- Correctly trigger the component's lifecycle hooks
- Trigger transition animations
Example
{{ text }}
When text When it changes, the element is replaced rather than reused, so a transition effect is triggered.
Notes
Keys should be unique and stable: the value of a key should not change with the data, otherwise it will affect Vue's performance and the virtual DOM reuse strategy.
Avoid using the index as a key: unless you are certain the order of list items will not change. Because the index is position-based, when the list order changes, the key also changes, causing Vue to fail to correctly reuse DOM nodes.
Example
{{ item.name }}
{{ item.name }}
Used together with v-for
key The difference between v-for , the following syntaxes are available:
Example
{{ item.name }}
{{ index }} - {{ item.name }}
{{ index }}. {{ key }}: {{ value }}
{{ n }}
Vue 3 Built-in Attributes