【问题标题】:vue.js: How to do calculation from object in an array?vue.js:如何从数组中的对象进行计算?
【发布时间】:2020-01-22 14:25:34
【问题描述】:
我尝试了不同的方法,但没有得到想要的结果。我想从每个数组中得到产品答案的总和,但我只得到第一个数组。这是我在 codepen 上的完整代码的链接。
https://codepen.io/Thinker95/pen/bGbOrJb
下面是我的代码:
Calculate(){
this.fights[0].consumption = this.fights[0].rating*this.fights[0].quantity*this.fights[0].operation;
this.answer = this.fights[0].consumption;
【问题讨论】:
标签:
javascript
arrays
vue.js
javascript-objects
vuetify.js
【解决方案1】:
你只计算数组的第一个元素。
你必须遍历它
把它放在你的计算函数中
this.fights.forEach((fight)=>{
this.fight.consumption = this.fight.rating*this.fight.quantity*this.fight.operation;
this.answer += this.fight.consumption
})
【解决方案2】:
当你做this.fights[0]时,你只使用第一场战斗。
你需要遍历fights来设置每场战斗的消耗并计算this.answer
new Vue({
el: "#app",
data(){
return {
fights: [
{ device:'Laptop', rating:1000, quantity: 2, operation: 4, consumption: ''},
{ device:'Television', rating:900, quantity: 4, operation: 6, consumption: ''},
],
answer: 0
}
},
methods: {
Calculate(){
this.answer = 0
this.fights.forEach(fight => {
fight.consumption = fight.rating * fight.quantity * fight.operation
this.answer += fight.consumption
})
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.10/vue.min.js"></script>
<div id="app">
<div v-for="fight in fights">
<h3>{{ fight.device }}</h3>
<p>Rating: {{ fight.rating }}</p>
<p>Quantity: {{ fight.quantity }}</p>
<p>Operation: {{ fight.operation }}</p>
<p>Consumption: {{ fight.consumption }}</p>
<hr>
</div>
<button @click="Calculate">calculate</button>
{{ answer }}
</div>