Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Vue 3 key Attribute

Vue 3 key Attribute

Vue3 Built-in Properties Vue 3 Built-in Attributes


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.


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


Use Cases

1. List Rendering

in v-for Using it in key is the most common scenario:

Example

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:

Example

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 }}


    Vue3 Built-in Properties Vue 3 Built-in Attributes