Using Vue keys

Posted on Updated on Vue.js by Gergő D. Nagy

Vue offers (and sometimes strongly suggests) using keys for in some scenarios. Let’s take a look when should we use the :key binding.

Using keys for loops

The most usual way to use a key binding is inside a loop. When we are using keys, Vue will reorder elements based on the order change of keys, and elements with keys that don’t exist will be removed.

Please note, in the same parent component, key duplications will cause render error.
<li v-for="(item, index) in array" :key="index">
    {{ item }}
</li>

Using keys for force replacement

This is a bit less common, however, when working with loops that are rendering components, using this properly can save us a bit of a headache.

Let’s say we have the JSON representation of Larvel models in an array and we loop through those and rendering an update form for all of them. Often I experienced if the rendered component is not uniquely keyed, on item removal/change the form contents can be mixed. To prevent this, let’s use a unique key – e.g. using the ID of the model, instead of their index in the array.

<data-form v-for="model in models" :key="model.id" :data="model">
    ...
</data-form>

Using keys for retriggering transitions

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

When the text will change, the transition will be triggered automatically. Without keys, the text would be replaced without restarting the transition.

Need a web developer? Maybe we can help, get in touch!