Search code examples
javascriptvue.jsvuejs2vue-componentv-for

Can't increase / decrease data property value in Vue


I am new in Vue.js and facing a simple problem in Vue reactivity. I am trying to increase or decrease a value in a data property and also update another dependent value in real-time. Here is my code demonstration:

https://codesandbox.io/s/crimson-http-srkz0?file=/src/App.vue

<div v-for="(product,index) in products" :key="index" style="padding-top:10px">
   <button @click="decrement(product.quantity)">-</button> 
   {{product.quantity}}
   <button @click="increment(product.quantity)">+</button>
   {{product.title}} 
   costs ${{calculateSubtotal(product.price,product.quantity)}}
</div>
data(){
  return{
    products:[
      {
       title:'ball',
       quantity: 2,
       price: 25
      },
      {
       title:'bat',
       quantity: 1,
       price: 79
      },
    ]
  }
},
methods:{
  increment(n){
    return n+=1;
  },
  decrement(n){
    return n-=1;
  },
  calculateSubtotal(price,quantity){
    return price*quantity
  }
}

Expected Output: The buttons should work to increase or decrease the value and calculate the costs in real-time. Can anybody help me ? Thanks in advance.


Solution

  • Pass the whole product to the methods:

    <button @click="decrement(product)">-</button> 
    {{product.quantity}}
    <button @click="increment(product)">+</button>
    {product.title}} 
    

    And modify them like this:

    increment(p){
       p.quantity += 1;
    },
    decrement(p){
       p.quantity -= 1;
    },
    

    Otherwise, the method is only receiving a copy of the value and modifying that instead of the object property.

    You could do it without any methods like this:

    <button @click="product.quantity--">-</button> 
    {{product.quantity}}
    <button @click="product.quantity++">+</button>
    {{product.title}}