Famurewa Taiwo
Famurewa Taiwo

Reputation: 1

How to sum values inside v-for statement (vuejs)

Here is my code below

<td v-for="config in configs" v-if="config">
    <input type="number" v-model="config.score" v-on:keyup="computeTestScores(allocation, $event)">
 </td>
<td><span class="subtotal"></span></td>`

how do i compute the subtotal? Secondly, if the values of any input changes, i want to be able update the total class;

Upvotes: 0

Views: 2738

Answers (2)

Rodris
Rodris

Reputation: 2858

You may sum the values of your array with the reduce function. The total will update automatically if any score changes.

<td><span class="subtotal">{{ configs.reduce((a, c) => a + parseInt(c.score), 0) }}</span></td>

Upvotes: 0

Lassi Uosukainen
Lassi Uosukainen

Reputation: 1688

You should not try to compute the sum with v-for. V-for is meant for presentation.

Instead add a computed value that calculates the subtotal. Inside the computed you should loop through the array, calculate the sum and return it. The computed property also calculates the new value automatically if any of the inputs change.

Upvotes: 2

Related Questions