【发布时间】:2017-04-21 10:16:22
【问题描述】:
我有一个组件,它保存单价、数量,并希望在视图中计算一个总计,但该视图不在组件内部。我能做些什么来实现这一目标? 每个组件都是动态生成的,这里有一个示例代码。 谢谢!
<table>
<tr is="item-grid" v-for='index in counter'></tr>
<tr><td v-text="sub_total"></td></tr>
<button @click="counter++" type="button">TEST ADD ROW</button>
</table>
<template id="item-template">
<tr>
<td><input type="text" class="form-control" v-model="inventory_name" readonly/></td>
<td><input type="text" class="form-control" v-model="sku"/></td>
<td><input type="text" class="form-control" v-model="qty"/></td>
<td><input v-model="unit_price"></input></td>
<td><span v-text="unit_total"></span></td>
<td><button @click="remove(this)" type="button">delete</button></td>
</tr>
</template>
<script>
var Item = {
template: '#item-template',
data: function(){
return {'qty': 0, 'unit_price': 0.00, 'inventory_name': '', 'sku': ''}
},
methods:{
remove: function(a){
console.log(a);
}
},
computed: {
unit_total: function(){
return this.qty * this.unit_price;
}
}
}
new Vue({
el: '#app',
props: ['item','sub_total','tax','grand_total'],
data: {
'counter': 1,
},
components: {
'item-grid': Item,
},
// computed: {
// sub_total: function(){
// return Item.unit_total++;
// }
// }
});
</script>
【问题讨论】:
-
嗯,最简单的方法是将用于计算的值保留在外部对象中,然后在需要进行计算的地方使用该对象中的值。
-
@BelminBedak 所有组件都是动态生成的,是否可以重新循环计算?