Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue.js How to calculate totals?

Tags:

vue.js

How can I calculate the total amount from an array?

I pass data to the child component as prop, and I am stuck here. When I console log prop, it returns a very complicated object . I tried this.values.reduce() function but it does not work.

<template>
<tr v-for="value in values"  >
      <th scope="row">{{$index+1}}</th>
      <td>{{value.name}}</td>
      <td>-</td>
      <td>${{value.total}}</td>
    </tr>
<tr>
    <th></th>
    <td><strong>Total:{{total}}</strong></td>
    <td>-</td>
    <td>-</td>
    </tr>
</template>

<script>

export default {



    props: ['values'],

      ready: function() {

    }

}
</script>
like image 825
OMahoooo Avatar asked Aug 24 '16 07:08

OMahoooo


2 Answers

In case anyone else is in the same situation as me I thought I'd add this answer. I needed to get the values from nested objects then push them to an array before reducing them:

total: function(){

  let total = [];

  Object.entries(this.orders).forEach(([key, val]) => {
      total.push(val.price) // the value of the current key.
  });

  return total.reduce(function(total, num){ return total + num }, 0);

}

This uses ES7 .entries to loop through the object which looked like this:

orders = {
    1: {title: 'Google Pixel', price: 3000},      
    2: {title: 'Samsung Galaxy S8', price: 2500},
    3: {title: 'iPhone 7', price: 5000}
  }

You can then display the total in your template with:

<span> {{total}} </span>
like image 142
Pixelomo Avatar answered Sep 17 '22 17:09

Pixelomo


var payments = new Vue({
            el: "#payments",
            data: {
                payments: [
                    { name: "houseRent", amount: 1000, is_paid: true },
                    { name: "houseRent", amount: 1500, is_paid: true },
                    { name: "houseRent", amount: 1200, is_paid: false },
                    { name: "houseRent", amount: 1070, is_paid: true },
                    { name: "houseRent", amount: 1040, is_paid: false }
                ]
            },
            computed: {
                totalAmount: function () {
                    var sum = 0;
                    this.payments.forEach(e => {
                        sum += e.amount;
                    });
                    return sum
                }
            }
        });`
like image 28
Ariphuz Xaman Tanin Avatar answered Sep 19 '22 17:09

Ariphuz Xaman Tanin