[Vuejs]-Vue v-bind class on event

0👍

Please try this logic if you have only single selected item

<span class="wishlist" @click="addToWishList(product.id)"
         :class="{selected : selectedProductId===product.id}">
    <i class="far fa-heart"></i>
</span>

// your data
data:()=>{
  return {
    selectedProductId:null
  }
}

//method
addToWishList:function(id){
  this.selectedProductId = id;
  // rest of your logic
  ...
}

If you have multiple select

<span class="wishlist" @click="addToWishList(product.id)"
         :class="{selected : selectedProductIds.indexOf(product.id)>-1}">
    <i class="far fa-heart"></i>
</span>

// your data
data:()=>{
  return {
    selectedProductIds : null
  }
}

//method
addToWishList:function(id){
  let index = this.selectedProductIds.indexOf(id);
  // remove if already added
  if(index>-1){
    this.selectedProductIds.splice(index,1);
  }else{
    this.selectedProductIds.push(id);
  }

  // rest of your logic
  ...
}

Leave a comment