[Vuejs]-In VueJS, is it fine to bind :key attribute to element value when I have array of unique strings or numbers?

0👍

In many cases using the entries of the array would be the best choice for the key.

The role of the key is to identify equivalent VNodes when a component re-renders. In practice this determines which old components are considered equivalent to which new components and which old DOM nodes and equivalent to which new DOM nodes.

In cases where you have an array of strings or numbers that don’t change it doesn’t matter too much what you use for the key. Using the index would give the same result as using the entries, though it may be slightly more convenient to use the entries.

In cases where the entries can change you need to be a lot more careful. If an array is sorted then it might make most sense to use the entries. Imagine that the list items animate their positions when the order changes. Using the entries would ensure that the elements animate appropriately. Even if you aren’t using animations it can be helpful to think in those terms to decide what makes for the most appropriate key.

On the other hand, if the strings are editable, e.g. via an <input>, then you could run into problems as every time a single character changes in the string it would cause the key for the element to no longer match and force new DOM nodes to be created.

0👍

You can een leave out the key in this case. Quote from https://v2.vuejs.org/v2/guide/list.html

It is recommended to provide a key attribute with v-for whenever possible, unless the iterated DOM content is simple, or you are intentionally relying on the default behavior for performance gains.

In your case the DOM content is simple so I shouldn’t use the key element

Leave a comment