Passer au contenu
Sur cette page

Built-in Special Attributes

key

The key special attribute is primarily used as a hint for Vue's virtual DOM algorithm to identify vnodes when diffing the new list of nodes against the old list.

  • Expects: number | string | symbol

  • Details

    Without keys, Vue uses an algorithm that minimizes element movement and tries to patch/reuse elements of the same type in-place as much as possible. With keys, it will reorder elements based on the order change of keys, and elements with keys that are no longer present will always be removed / destroyed.

    Children of the same common parent must have unique keys. Duplicate keys will cause render errors.

    The most common use case is combined with v-for:

    template
    <ul>
      <li v-for="item in items" :key="item.id">...</li>
    </ul>
    

    It can also be used to force replacement of an element/component instead of reusing it. This can be useful when you want to:

    • Properly trigger lifecycle hooks of a component
    • Trigger transitions

    For example:

    template
    <transition>
      <span :key="text">{{ text }}</span>
    </transition>
    

    When text changes, the <span> will always be replaced instead of patched, so a transition will be triggered.

  • See also: Guide - Rendu de liste - Maintenir l'état avec key

ref

Denotes a ref du template.

  • Expects: string | Function

  • Details

    ref is used to register a reference to an element or a child component.

    In Options API, the reference will be registered under the component's this.$refs object:

    template
    <!-- stored as this.$refs.p -->
    <p ref="p">hello</p>
    

    In Composition API, the reference will be stored in a ref with matching name:

    vue
    <script setup>
    import { ref } from 'vue'
    
    const p = ref()
    </script>
    
    <template>
      <p ref="p">hello</p>
    </template>
    

    If used on a plain DOM element, the reference will be that element; if used on a child component, the reference will be the child component instance.

    Alternatively ref can accept a function value which provides full control over where to store the reference:

    template
    <ChildComponent :ref="(el) => child = el" />
    

    An important note about the ref registration timing: because the refs themselves are created as a result of the render function, you must wait until the component is mounted before accessing them.

    this.$refs is also non-reactive, therefore you should not attempt to use it in templates for data-binding.

  • See also:

is

Used for binding composants dynamiques.

Built-in Special Attributesa chargé