mafortis
mafortis

Reputation: 7128

How calculate numbers in Vue 2

I have loop of data and I want to calculate numbers of my data, the problem is that I cannot use + - in my calculator they come with the numbers like:

5.000
-2.000
1.000

so result should be 4.000

see the minus and plus comes with the numbers i need a solution for that.

code

<tbody>
                <tr v-for="(history,index) in histories" @key="index">
                    <td width="50" class="text-center">{{index+1}}</td>
                    <td class="text-center" width="100">
                        {{history.created_at}}
                    </td>
                    <td class="text-center" width="300">Rp. {{ formatPrice(history.balance) }}</td>
                    <td class="text-center">{{history.note}}</td>
                </tr>
</tbody>

PS: I do not need * / in my calculator, simple + - would be enough. thanks in advance.

Upvotes: 0

Views: 76

Answers (1)

F.Igor
F.Igor

Reputation: 4350

In the methods section, you can do a loop over histories and sum the values of each .balance attribute:

methods: { 
   calculateTotal: function(histories){
     var sum=0;
     for(var i=0;i<histories.length;i++){
       sum += histories[i].balance;
     }
     return sum;
   }

Then you can use it in your view, after the history rows:

{{calculateTotal(histories)}}

Note: If histories is part of the component data, you can access this.histories inside the calculateTotal method, without need to pass it as an argument.

Now, the method will be:

calculateTotal: function(){
     var sum=0;
     for(var i=0;i<this.histories.length;i++){
       sum += this.histories[i].balance;
     }
     return sum;
   }

And the call from view will be only

{{calculateTotal()}}

Upvotes: 1

Related Questions