Reputation: 447
I am populating a dropdown with an array, however I am confused as to which key i should use in the v-for.
I have tried multiple keys and even without a key. Everything seems to work, but what would be best practice?
<select class="period-control" v-model="selected">
<option v-for="month in car.months" :key="month.id">{{ month }}</option>
</select>
asyncData(context) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve({
car: [
{
id: "1",
brand: "VW",
model: "Transporter",
variant: "Sport",
thumbnail:
"http://pluspng.com/img-png/cargo-van-png-van-png-transparent-image-1878.png",
mprice: "2700",
dpayment: "5400",
months: [
{ month: "12 måneder" },
{ month: "24 måneder" },
{ month: "36 måneder" }
]
},
{
id: "2",
brand: "Nissan",
model: "Tekna",
variant: "Sport",
thumbnail:
"http://pluspng.com/img-png/cargo-van-png-van-png-transparent-image-1878.png",
mprice: "3000",
dpayment: "5400",
months: ["12 måneder", "24 måneder"]
}
].find(el => el.id === context.params.id)
});
}, 1500);
});
}
Ì have no errors, the dropdown is outputting the correct array.
Upvotes: 0
Views: 48
Reputation: 2366
The 'best practice' requires you to use a key that is unique. In your case, you could use the id of each element in the array. The reason for this is, it allows vue to keep track of all the elements between the dom and virtual dom in the event when any one of them is removed.
As a last resort, you could also use the index of the items, but bear in mind that it might lead to some rendering issues as vue will find it difficult to uniquely indentify elements and track the ones that have been removed.
When Vue is updating a list of elements rendered with v-for, by default it uses an “in-place patch” strategy. If the order of the data items has changed, instead of moving the DOM elements to match the order of the items, Vue will patch each element in-place and make sure it reflects what should be rendered at that particular index. This is similar to the behavior of track-by="$index" in Vue 1.x.
This default mode is efficient, but only suitable when your list render output does not rely on child component state or temporary DOM state (e.g. form input values).
To give Vue a hint so that it can track each node’s identity, and thus reuse and reorder existing elements, you need to provide a unique key attribute for each item:
see https://v2.vuejs.org/v2/guide/list.html#Maintaining-State
Upvotes: 1