Skip to content
Advertisement

Show updated value on click

I have a function that adds items to a cart, when an item is already in the cart, I expect it to only add 1 to quantity of that item(which it does).

The problem is I can’t view the updated quantity until there is another action such as adding another item to the cart.

I followed solutions from similar question but still doesn’t work for me.

I want to be able to view the updated value immediately the item is added.

addItemToCart : function(item){
       if(this.cart.includes(item)){
            item.quantity += 1;
            console.log(item.quantity);
        }
       else{
           this.cart.push(item);
          this.set(item.quantity = 1);
       }
},

HTML:

 <ul>
    <li>Cart is empty</li>
    <li v-for="item in cart">
        {{item.name }}
        <span class="pull-right">
        ({{ item.price }} x {{ item.quantity }})
        <i class="glyphicon glyphicon-remove cart-item-action" @click="removeItemFromCart(item)"></i>
    </span>
    </li>
</ul>  

Advertisement

Answer

I believe this is happening because of caveats of change detection in vue.

Due to limitations in JavaScript, Vue cannot detect the following changes to an array:

  1. When you directly set an item with the index, e.g. vm.items[indexOfItem] = newValue

  2. When you modify the length of the array, e.g. vm.items.length = newLength

So what you need to do is, you can pass index of that cart item in the function addItemToCart and use Vue.set like following:

addItemToCart : function(item){
       if(this.cart.includes(item)){
            var index = this.cart.indexOf(item)
            this.cart[index] += 1
            Vue.set(this.cart, index, this.cart[index])
            //or 
            //  this.$set(this.cart, index, this.cart[index])

            //or 
            //  this.cart.splice(index, 1, this.cart[index])
            console.log(item.quantity);

        }
       else{
          this.cart.push(item);
          this.set(item.quantity = 1);
       }
},
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement