无法增加/减少 Vue 中的数据 属性 值

Can't increase / decrease data property value in Vue

我是 Vue.js 的新手,在 Vue 反应性方面面临一个简单的问题。我正在尝试增加或减少数据 属性 中的值,并实时更新另一个相关值。这是我的代码演示:

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
  }
}

预期输出: 这些按钮应该可以增加或减少价值并实时计算成本。有谁能够帮我 ?提前致谢。

将整个 product 传递给方法:

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

并像这样修改它们:

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

否则,该方法只接收值的副本并修改它而不是对象 属性。

你可以不用像这样的任何方法来做到这一点:

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