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 :

const ar = ref([A, B, C]);

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:

// I create a dynamic array from a v-model, with some minor transformation. 
const inputRef = ref(
  props.modelValue.map((val) => ({ ...val, value: val.end - val.start }))
);
// This callback is triggered when pressing the delete button in my DOM component.
const removeValue = (index) => {
  inputRef.value.splice(index, 1);
};

This is how I render the array in my DOM:

   <div
    v-for="(item, index) in inputRef"
    :key="index"
    class="flex flex-col items-center w-full">
     <!-- stuff -->   
   </div>

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

 <div
     v-for="(item, index) in inputRef"
     :key="item.<some unique property>"
     class="flex flex-col items-center w-full">
     <!-- stuff -->   
  </div>

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

<div
   v-for="(item, index) in inputRef"
   :key="item.value"
   class="flex flex-col items-center w-full">
   <!-- stuff -->   

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