[英]vue.js: How to do calculation from object in an array?
I have tried different approaches but I'm not getting the desired result.我尝试了不同的方法,但没有得到想要的结果。 I want to get the total sum of the product answer from each array but I'm only getting for the first array.
我想从每个数组中得到产品答案的总和,但我只得到第一个数组。 Here is the link to my full code on codepen.
这是我在 codepen 上的完整代码的链接。
https://codepen.io/Thinker95/pen/bGbOrJb https://codepen.io/Thinker95/pen/bGbOrJb
Below is my code:下面是我的代码:
Calculate(){
this.fights[0].consumption = this.fights[0].rating*this.fights[0].quantity*this.fights[0].operation;
this.answer = this.fights[0].consumption;
You calculate only first element of the array.您只计算数组的第一个元素。
You have to loop through it你必须遍历它
Put this inside your calculate function把它放在你的计算中 function
this.fights.forEach((fight)=>{
this.fight.consumption = this.fight.rating*this.fight.quantity*this.fight.operation;
this.answer += this.fight.consumption
})
When you do this.fights[0]
, you only use the first fight.当你这样做
this.fights[0]
时,你只使用第一场战斗。
You need to iterate over fights
to set the consumption for each fight and compute this.answer
您需要遍历
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.