我是 Vue.js 新手,在 Vue react 性方面面临一个简单的问题。我正在尝试增加或减少数据属性中的值,并实时更新另一个依赖值。这是我的代码演示:
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
}
}
预期输出: 这些按钮应该可以增加或减少值(value)并实时计算成本。有谁能够帮助我 ?提前致谢。
最佳答案
将整个产品
传递给方法:
<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}}
关于javascript - 无法增加/减少Vue中的数据属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61287124/