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.
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;
When you do this.fights[0]
, you only use the first fight.
You need to iterate over fights
to set the consumption for each fight and compute 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>