我有一个遍历产品列表的表。对于表格中的每个产品,我都有一个输入,用户可以在这里选择他想要多少单位的产品在这一行。然后,我在表中有另一个单元格表示总数,该单元格是根据用户数量乘以单价计算得出的。这是我的桌子。
<table class="table table-striped table-borderd">
<template v-for="(c, catIndex) in products">
<tr>
<th>{{c.category}}</th>
<th>{{c.bulkSize}}</th>
<th>Price</th>
<th>Quantity</th>
<th>Total</th>
</tr>
<tr v-for="(p, productIndex) in c.productList">
<td>{{p.description}}</td>
<td>{{p.productSize}}</td>
<td>{{p.productPrice}}</td>
<td>
<input v-on:keyup='calculateTotal(catIndex, productIndex)' type="text" v-model="p.quantity" placeholder="Quantity">
</td>
<td>
<input
type="text"
readonly
v-model="p.total">
</td>
</tr>
</template>
</table>然后在我的JavaScript中,我计算keyup上的总数。下面是代码。
calculateTotal: function(categoryIndex, productIndex) {
let currentCategory = this.products[categoryIndex];
let currentProduct = currentCategory.productList[productIndex];
currentProduct.total = currentProduct.quantity * currentProduct.productPrice;
console.log(this.products[categoryIndex].productList[productIndex].total);
}console.log()向我显示了正确的值,但是绑定到total的单元格从不更新。
我需要指出的是,quantity键和total键都是通过v-model添加到产品对象中的。
我哪里错了?
编辑:基于下面的回答,我添加了这段代码来尝试解决这个问题,但它不起作用。
created: function() {
$.get('some endpoint', data => {
this.customers = data.customers;
this.locations = data.locations;
this.products = data.products;
this.products.forEach(cat => {
cat.productList.forEach(product => {
product.total = undefined;
})
})
});
},发布于 2016-12-07 23:43:45
您可以通过向您的产品添加total属性来修复它。它可能是0,甚至是undefined,但是,它必须在那里。这是设计好的。github上的相关问题:https://github.com/vuejs/vue/issues/1797和https://github.com/vuejs/vue/issues/3732。
发布于 2016-12-07 23:43:18
已修复:http://jsbin.com/nilutegexo/1/edit?html,js,console,output
这是因为您完全动态地创建列表,并且它导致了反应性问题。基本上,您必须启动total: 0,它工作得非常好。
https://stackoverflow.com/questions/41021238
复制相似问题