Skip to content
Advertisement

Vue 3 arrays – Deletion from array removes wrong DOM element

When removing an element from a ref array in Vue, it removes the right one in the JS side of things, however in the DOM, it removed the last one of the list. I have no clue why it removes the wrong element.

For example :

JavaScript

When I remove B and logging that deletion, I get an array [A, C]. However, on my webapp, the rendered elements have the values of [A, B] instead of [A, C]. I have used different ways of removing elements from an array, the one that worked the best is obviously splice but like I said, my component renders the [A,B] elements instead of [A,C].

This is the code:

JavaScript

This is how I render the array in my DOM:

JavaScript

I struggle to understand why the DOM does not match the array that is logged. Is it something I am missing from Vue 3?

Advertisement

Answer

You are using index as key you should replace it with some thing that is more unique to each element like in case if elements in array are objects and then you might have an id property or value property or some other property that is unique to each element you should you that in like

JavaScript

or incase of input ref considering value for each element is unique then your could should be

JavaScript

for understanding why you should not use index for key you can read this section of vue docs maintaining-state-with-key

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement