Reputation: 160
I have a dynamic component with Vue Croppa.
<croppa v-for="(image, key) in images" :key="key" ...props></croppa>
If I add an element in images
, it add a new croppa components and work perfect.
The problem is when I try to remove an element.
For example, if I added 3 images:
images: [
'image1.png',
'image2.png',
'image3.png,
]
if I deleted image2 (index: 1)
it remove image3.
What I need to do to preserve all config (initial-image, position, flipX, etc...) of croppa by position?
Thanks
Upvotes: 0
Views: 346
Reputation: 4732
Using index
argument of v-for
directive (in your case key
) is reliable way to set item key
attribute only if looped array (in your case images
) is not going to be mutated.
In example above, when images
length changes indexes of rendered items stay the same. Meaning, if second item has been deleted, renderer can notice changes of key indexes
from 0, 1, 2
to 0, 1
Thus, the item with last index 2
is removed.
In order to achieve expected behavior, key
attribute should be set to a unique value. For array of objects it is usually an id
or any unique property. For array of strings (if values in array are unique) the key
attribute can be set to that value. Example:
<croppa
v-for="image in images"
:key="image"
/>
In case if some values in that array are not unique (which should be assumed if values come from external source - API, user input, etc), key
attribute should be set to concatenated value and index. Example:
<croppa
v-for="(image, index) in images"
:key="`${image}${index}`"
/>
Upvotes: 1