我有一个 vue js 项目,它就像一个购物车。 我想计算每行产品的小计。
我的html代码:
<div id="app">
<table border="1">
<thead>
<tr>
<th>#</th>
<th>title</th>
<th>price</th>
<th>quantity</th>
<th>subtotal</th>
</tr>
</thead>
<tbody>
<tr v-for="product in products" :key="product.id">
<td>{{ product.id }}</td>
<td>{{ product.title }}</td>
<td>{{ product.price }}</td>
<td><input type="number" v-model="product.quantity"></td>
<td>{{ product.subtotal }}</td>
</tr>
</tbody>
</table>
</div>
我的js代码是:
var app = new Vue({
el: '#app',
data: {
products: [
{
"id": 1,
"title": "first",
"price": 151,
"quantity": 0,
"subtotal": 0
},
{
"id": 2,
"title": "second",
"price": 152,
"quantity": 0,
"subtotal": 0
},
{
"id": 3,
"title": "another record",
"price": 0,
"quantity": 0,
"subtotal": 0
},
{
"id": 4,
"title": "hello",
"price": 0,
"quantity": 0,
"subtotal": 0
},
{
"id": 5,
"title": "world",
"price": 0,
"quantity": 0,
"subtotal": 0
}
]
},
computed:{
'product.subtotal': function(){
return product.quantity * product.price;
}
}
});
如何通过更改数量来计算任何产品的小计? 我想将计算出的小计保存到product.subtotal 属性中。
这是 jsfiddle 链接: https://jsfiddle.net/s38wLk49/
最佳答案
错误(嗯,不完整):
将 {{product.subtotal }}
更改为 {{product.price * Product.quantity }}
不会吗?
由于他想要实际更改数据,而不仅仅是显示,这就是我尝试过的并且它对我有用:
watch:{
products:{
handler:function(newval,oldval) {
this.products.forEach(p => {
p.subtotal = p.price * p.quantity;
});
}, deep:true
}
}
Vue 支持监视对象的属性,但据我所知,它不适用于对象的数组(我可能是错的!)。
关于javascript - 在 vue.js 中计算小计,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49259045/