MauirceA
MauirceA

Reputation: 321

Vue: Adding class to one item in v-for

I have a list of items in a v-for loop. I have a function on @click that will delete the item but I want to give it a class when I click it to change the background color for a short time so the user knows they clicked that item and it's deleting. In my deleteItem function, I set deletingItem to true but that obviously creates an issue because it will apply that class to all the divs in the in v-for. What is the best way to solve it so that it only gets applied to the div I click on?

   <div :class="{'box': true, 'deleting-item': deletingItem}" v-for="(item,index) in items">
        <div @click="deleteItem(item,index)>Delete</div>
    </div>

Upvotes: 0

Views: 1208

Answers (1)

user10706046
user10706046

Reputation:

You need to save the clicked item in a data property

<template>
<div>
  <div v-for="(item, index) in items">
    <button @click="deleteItem(index)" :class="{'delete-in-progress-class': index === indexOfDeletedItem}> {{item}} </button> 
  </div>
</div>
</template>
<script>
export default {
  data() {
    return {
      items: ['a', 'b', 'c']
      indexOfDeletedItem: null
    }
  },
  methods: {
    deleteItem(index) {
      this.indexOfDeletedItem = index;
      setTimeout(() => { this.items.splice(index, 1); this.indexOfDeletedItem = null }, 1000); //delete item after 1s
    }
  }
}
</script>
<style>
.delete-in-progress-class {
  background: red;
}
</style>

Obviously the solution above is naive. It'll probably go crazy if the user wants to delete many items in a short time, since the indices of an array shift around when you delete something.

But hopefully it'll give you an idea of how to conditionally apply styles in a list.

Upvotes: 2

Related Questions