In Vue.js, when dealing with lists of elements like v-for
, it's important to provide a unique key prop for each element. Keys are special attributes that allow Vue to identify which items have changed, added, or removed, and optimize the updates accordingly.
When using v-for
to iterate over an array, you should always include a key attribute with a unique value for each item in the list. Here's how you can do it:
<template>
<ul>
<li v-for="(item, index) in items" :key="index">{{ item }}</li>
</ul>
</template>
In this example, we're using the index
of each item as the key. However, if your list contains items with unique IDs (like id
from a database), it would be better to use that:
<template>
<ul>
<li v-for="(item, index) in items" :key="item.id">{{ item }}</li>
</ul>
</template>
Remember to always assign a key prop when iterating over lists in Vue.js to improve performance and maintain state across updates.