Skip to content
Advertisement

splice in javascript(vue) not working as expected after adding class dynamically

I’m trying to delete an element from an array using array splice method. I’m also using animate.css and I dynamically add the class ‘fadeOutDown’ before deleting the element. Then I’m using a timeout function to wait for the animation to complete and remove the element from the array using index.

When I click the delete button the index of the element performs the animation but additionally the very next index is also removed from the DOM but not from the array.

Below the html and js-function for removing the element:

<ul class="list-group todos mx-auto text-light">
  <li v-for="(todo , i) in filterTodo" :key="i" 
   class="list-group-item d-flex justify-content-between align-items-center 
   animated slideInUp slow">
   <span>{{ todo }}</span>
   <i @click="removeTodo(i , $event)" class="fa fa-trash-o delete">x</i>
  </li>
</ul>

removeTodo(id, e) {
  e.target.parentElement.classList.remove("slideInUp");
  e.target.parentElement.classList.add("fadeOutDown");
  setTimeout(() => {
    this.todos.splice(id, 1);
  }, 1000);
}

Advertisement

Answer

The problem is that using index as key.

<li
  v-for="(todo , i) in filterTodo"
  :key="i" // this will make that bug.
...

You should not use index as key especially when array can be updated.

Instead of using index as key, it is better to use unique string or index in each filterTodo item.

If todo is unique, you can use that as key directly like below:

<li
  v-for="(todo , i) in filterTodo"
  :key="todo"
...
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement