How to calculate the total in a filter in Vue js

Asked

Viewed 46 times

0

This application Vue calculates totals in a list as below within methods:

somaTotal(){
    let amounts = this.transactions.map(transaction => transaction.valor);
    return this.total = amounts
           .reduce((acc, item) => (acc += parseFloat(item)), 0)
           .toFixed(2);
}

the HTML code showing the total is as follows:

<td align="right"> 
    <b> 
        {{parseFloat(somaTotal())
           .toLocaleString('pt-BR', { style: 'currency', currency: 'BRL' })
        }} 
    </b>
</td>

Has this filter that shows the list according to the text we typed:

computed: {
           filteredTransactions (){
              if(this.searchQuery){
                  return this.transactions.filter((transaction)=>{
                  return transaction.tipo.startsWith(this.searchQuery);
                 })
              }else{
                  return this.transactions;
              }
            }
      },

How to calculate the total inside the filter? Totalizing based on the filtered values?

1 answer

1

Suffice it to add

.reduce((acc, item) => (acc += parseFloat(item)), 0)
.toFixed(2);

at the end of that computed. You can adapt the method somaTotal to receive an array and do so:

methods: {
    somaTotal(transactions) {
      let amounts = (transactions || this.transactions).map(transaction => transaction.valor);
      return this.total = amounts
        .reduce((acc, item) => (acc += parseFloat(item)), 0)
        .toFixed(2);
    }
  },
  computed: {
    filteredTransactions() {
      let transactions = this.transactions;
      if (this.searchQuery) {
        transactions = this.transactions.filter((transaction) => {
          return transaction.tipo.startsWith(this.searchQuery);
        })
      }
      return somaTotal(transactions);
    }
  },
  • Great. I’ll test it.

  • You defined somaTotal and methods and called somaValor.

  • Also, I want the calculated total inside the filter. As you did, calculate the total outside.

  • @Flaviocardoso my mistake, I wanted to say the same name as the method you already had. I corrected.

  • @Flaviocardoso how so "calculated out"? The methods can and should be used as tools for other methods, computed, etc

Browser other questions tagged

You are not signed in. Login or sign up in order to post.