YouTip LogoYouTip

Vue3 Key

[![Image 1: Vue3 Built-in attribute](https://example.com/images/up.gif) Vue3 Built-in attribute](https://example.com/vue3/vue3-builtin-attributes.html) * * * The `key` attribute is a special critical attribute in Vue's virtual DOM algorithm, mainly used to help Vue identify the uniqueness of each node, thereby efficiently updating the virtual DOM. * * * ## Basic Description The `key` attribute is used to provide a unique identifier for Vue components or elements. In list rendering, each element in a `v-for` loop should have a unique `key` attribute. * **Type**: String | Number * **Role**: 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 diff, without `key`, Vue uses an algorithm that minimizes element movement, trying to reuse elements of the same type in place. With `key`, Vue will reorder elements based on the order change of keys, and will remove elements whose keys no longer exist. Sibling elements under the same parent must have unique keys. Duplicate keys will cause rendering errors. * * * ## Basic Usage The most common usage is with `v-for`: ## Example
  • {{ item.name }}
* * * ## Usage Scenarios ### 1、List Rendering Using `key` in `v-for` is the most common scenario: ## Example ### 2、Forcing Element Replacement `key` can also be used to force replace an element or component instead of reusing it. This is useful in the following scenarios: * Properly triggering component lifecycle hooks * Triggering transition animations ## Example When `text` changes, the `` element will be replaced instead of being reused, thus triggering the transition effect. * * * ## Notes > **key should be unique and stable**: The value of key should not change with data changes, otherwise it will affect Vue's performance and virtual DOM reuse strategy. > **Avoid using index as key**: Unless you clearly know that the order of list items will not change. Because index is position-based, when the list order changes, the key will also change, causing Vue to fail to correctly reuse DOM nodes. ## Example
  • {{ item.name }}
  • {{ item.name }}
  • * * * ## Using with v-for When using `key` with `v-for`, there are several syntax options: ## Example
  • {{ item.name }}
  • {{ index }} - {{ item.name }}
  • {{ index }}. {{ key }}: {{ value }}
  • {{ n }} * * * [![Image 2: Vue3 Built-in attribute](https://example.com/images/up.gif) Vue3 Built-in attribute](https://example.com/vue3/vue3-builtin-attributes.html)
    ← Vue3 V BindPytorch Attention β†’