我正在尝试使用vuejs对在v-for内部计算的值求和,但是我认为它不起作用,因为我无法从v-for中的计算值访问该值。
我需要在{{total}}中显示用户的总价值,即v-model.number="totalItem(item)"
有人可以给我一些指示吗?感谢。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<div id="app">
<button v-on:click="add">ADD ROW</button>
<p>$: {{ total }}</p>
<ul>
<li v-for="(item, index) in items">
<input type="text" v-model="item.name">
<input type="number" v-model.number="item.quantity" min="1">
<input type="number" v-model.number="item.price" min="0.00" max="1000000000.00" step="0.01">
<input type="number" v-model.number="totalItem(item)" readonly>
<button v-on:click="remove(index)">X</button>
</li>
</ul>
<pre>{{ items | json}}</pre>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<script src="vuejs.js"></script>
</body>
</html>
javascript - vuejs.js
new Vue({
el: '#app',
data: {
items: [{name: '', quantity: '', price: ''}]
},
methods: {
add: function () {
this.items.push({
name: '',
quantity: '',
price: '',
subTotal: ''
})
},
remove: function (index) {
this.items.splice(index, 1)
},
totalItem: function (item) {
return item.price * item.quantity;
}
},
computed : {
total: function() {
let sum = 0;
return this.items.reduce((sum, item) => sum + item.price, 0);
}
}
})
答案 0 :(得分:5)
我找到了答案。这很简单。
const Memo = (f, memo) => () =>
memo === undefined
? (memo = f (), memo)
: memo
const Yield = (value, next = Return) =>
({ done: false, value, next: Memo (next) })
const Return = value =>
({ done: true, value })
const Range = (min = 0, max = Infinity) =>
min > max
? Return ()
: Yield (min, () => Range (min + 1, max))
const MappedIterator = (f, it = Return ()) =>
it.done
? Return ()
: Yield (f (it.value), () => MappedIterator (f, it.next ()))
const ConcatIterator = (x = Return (), y = Return ()) =>
x.done
? y
: Yield (x.value, () => ConcatIterator (x.next (), y))
const Generator = function* (it = Return ())
{
while (it.done === false)
(yield it.value, it = it.next ())
return it.value
}
const it =
MappedIterator (x => x * x, Range (1, 3))
console.log (Array.from (Generator (it)))
// [ 1, 4, 9 ]
console.log (Array.from (Generator (ConcatIterator (it, it))))
// [ 1, 4, 9, 1, 4, 9 ]
答案 1 :(得分:2)
在父组件中执行类似的操作:
computed: {
total: function(){
return this.items.reduce(function(prev, item){
return sum + item.price;
},0);
}
}
答案 2 :(得分:2)
- 对于
醇>
computed: {
totalItem: function(){
let sum = 0;
for(let i = 0; i < this.items.length; i++){
sum += (parseFloat(this.items[i].price) * parseFloat(this.items[i].quantity));
}
return sum;
}
}
- 的ForEach
醇>
computed: {
totalItem: function(){
let sum = 0;
this.items.forEach(function(item) {
sum += (parseFloat(item.price) * parseFloat(item.quantity));
});
return sum;
}
}
答案 3 :(得分:0)
短 foreach,你可以在其中为 vuex 放入 getters.js
totalInvoice: (state) => {
let sum = 0
state.itens.forEach( (item) => sum += (item.value) )
return sum
}