Matheus Barem
Matheus Barem

Reputation: 1627

calculate some fields in array of objects from v-for with vue.js

I'm new with Vue.js and i'm using a v-for to iterate an array of objects, but i need to calculate a single field (precoPorKg) in this v-for.

to calculate this i need that input item.quantidade had some value and after this, i need to make this operation:

(item.quantidade * item.valorUnitario)/( item.quantidade * item.pesoUnitario)

My v-for:

 <tr v-for="(item, index) in step2">
     <td>{{ item.produto }}</td>
     <td><input type="text" v-model="item.quantidade"></td>
     <td>{{ item.valorUnitario }}</td>
     <td>{{ item.pesoUnitario }}</td>
     <td>{{ item.cubagemUnitaria }}</td>
     <td>{{ calcPrecoPorKg(index, item) }}</td> 
 </tr>

my vue component (i'm trying to make this operation in computed, but doesn't work):

   new Vue({
                el: '#app', 
                data(){
                step2 : [
                  {
                    produto: 'A70-5',
                    descricao: 'bola de basquete',
                    ncm: '950.6',
                    quantidade: '',
                    valorUnitario: '0,78',
                    pesoUnitario: '0,430',
                    cubagemUnitaria: '0,00',
                    precoPorKg: '',
                  }
             ],
         computed: {
            calcPrecoPorKg: function (index, item) {
                return (item.quantidade * item.valorUnitario)/( item.quantidade * item.pesoUnitario);
                     }
                }

    })

Upvotes: 1

Views: 451

Answers (1)

Renaud
Renaud

Reputation: 1299

computed properties do not take any parameters. What you need is just a method.

methods: {
  calcPrecoPorKg(item) {
    return (item.quantidade * item.valorUnitario)/( item.quantidade * item.pesoUnitario);
  }
}

Upvotes: 2

Related Questions