What's a unique key in vue.js used for?

Ordinarily in a v-for loop, a change in the ordering of your array elements can result in undesired behavior. Imagine, for example, if your child component happened to be a form with inputs containing data that you've filled in. If you reorder your array, then that input information doesn't move with your array elements! You would expect that when you reorder your array, any changes made in the child components would move with those array elements.

Having a unique key solves this problem. The key acts as a sort of flag that tells Vue "if the data associated with this child component is moved somewhere else, then move the component along with it to preserve the changes that already exist".

This is all explained in the documentation. I highly encourage you to read this section carefully.

Recommended is that you do not use the array index as the unique id value as that is essentially the same as using no key at all. Instead, include an id field in your data that you initialize from the very beginning. Then, you can do something like :key="item.id" or :key="'child-component-'+item.id".

Tags:

Vue.Js