如何计算vue组件的总数? Vue.JS 2
How to calculate the total in vue component ? Vue.JS 2
我的vue组件,你可以看下面:
<template>
<div>
<div class="panel-group" v-for="item in list">
...
{{ total = 0 }}
<tr v-for="product in item.products">
...
<td>
<b>Price</b><br>
<span>{{ product.quantity * product.price }}</span>
</td>
</tr>
{{ total += (product.quantity * product.price) }}
<tr>
<td colspan="3" class="text-right">
<b>Total: {{ total }} </b>
</td>
</tr>
</div>
</div>
</template>
<script>
export default {
...
computed: {
list: function() {
return this.$store.state.transaction.list
},
...
}
}
</script>
我尝试像上面的代码
但是,好像还是不对
如何正确解决?
我还是 vue.js 2
的新手
使用另一个计算属性
<script>
export default {
...
computed: {
list: function() {
return this.$store.state.transaction.list
},
total: function() {
return this.$store.state.transaction.list.reduce(function(sum, item) {
sum += item.products.reduce(function(tmp, product) { tmp += product.quantity * product.price; return tmp; }, 0);
return sum;
}, 0);
}
...
}
}
</script>
使用嵌套 Array.reduce 获取您的结构的总数,其中列表有很多项目,一个项目有很多产品
因为,TypeError: this.$store.state.transaction.list.reduce is not a function
是 Frank 的回答中标记的错误,我认为 this.$store.state.transaction.list
不是 Array
,而是 object
,因为 v-for
遍历了两者.
total: function() {
var list = this.$store.state.transaction.list
var sum = 0
for(var listProps in list) {
list[listProps].products.forEach(function (product) {
sum += product.pivot.quantity * product.pivot.price
})
}
return sum;
}
我的vue组件,你可以看下面:
<template>
<div>
<div class="panel-group" v-for="item in list">
...
{{ total = 0 }}
<tr v-for="product in item.products">
...
<td>
<b>Price</b><br>
<span>{{ product.quantity * product.price }}</span>
</td>
</tr>
{{ total += (product.quantity * product.price) }}
<tr>
<td colspan="3" class="text-right">
<b>Total: {{ total }} </b>
</td>
</tr>
</div>
</div>
</template>
<script>
export default {
...
computed: {
list: function() {
return this.$store.state.transaction.list
},
...
}
}
</script>
我尝试像上面的代码
但是,好像还是不对
如何正确解决?
我还是 vue.js 2
的新手使用另一个计算属性
<script>
export default {
...
computed: {
list: function() {
return this.$store.state.transaction.list
},
total: function() {
return this.$store.state.transaction.list.reduce(function(sum, item) {
sum += item.products.reduce(function(tmp, product) { tmp += product.quantity * product.price; return tmp; }, 0);
return sum;
}, 0);
}
...
}
}
</script>
使用嵌套 Array.reduce 获取您的结构的总数,其中列表有很多项目,一个项目有很多产品
因为,TypeError: this.$store.state.transaction.list.reduce is not a function
是 Frank 的回答中标记的错误,我认为 this.$store.state.transaction.list
不是 Array
,而是 object
,因为 v-for
遍历了两者.
total: function() {
var list = this.$store.state.transaction.list
var sum = 0
for(var listProps in list) {
list[listProps].products.forEach(function (product) {
sum += product.pivot.quantity * product.pivot.price
})
}
return sum;
}