Reputation: 1003
I created fiddles to show the unexplicable behaviour:
https://jsfiddle.net/o7c9mwzf/27/
When I click unshift, I prepend an element to my items array. then I click set data to set its data, and finally when I click unshift again the element will be unshifted and keep its data.
https://jsfiddle.net/o7c9mwzf/25/
In this fiddle I put my component inside a div, and the v-for is on the div, like so:
<div v-for="item in items"><comp :key="item.uuid"/></div>
and in this case, when I unshift the array, the items that are already in the array lose their data.
Is there any explanation for this behaviour? I couldn't find any in the docs.
Upvotes: 0
Views: 131
Reputation: 6853
The key are supposed to be on root component of the v-for
element, so in this case it's supposed to be the div
, not the comp
<div v-for="item in items" :key="item.uuid"><comp /></div>
Or you can put the :key
on the comp
if you are using template
instead
<template v-for="item in items" :key="item.uuid"><comp /></template>
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
From: https://v3.vuejs.org/guide/list.html#maintaining-state
Since you put the key
on the comp
, the state on the parent element (div
) isn't maintained.
Upvotes: 2