Home > Blockchain >  How can I sum a input values created dynamically with Vuejs
How can I sum a input values created dynamically with Vuejs

Time:12-15

I have a list that I created like this:

<tbody>
  <tr v-for="(post, index) in posts" v-bind:index="index">
    <td>{{ post.rut }}</td>
    <td>{{ post.names }} {{ post.father_lastname }} {{ post.mother_lastname }}</td>
    <td>
       <input type="text" @blur="handleBlur(post.amount)"  id="exampleInputEmail1" v-model="post.amount" placeholder="Ingresa el monto">
    </td>
  </tr>
</tbody>

I have a method like this one in Vuejs:

handleBlur(value) {
  this.total_inputs = parseInt(this.total_inputs)   parseInt(value);
},

The thing is that if I edit any input it adds correctly I mean:

If it was 0.. and I add a value 3 in the input it will say 3 0 = 3 etc...

The thing is that I just do not need to add because If I edit same input that it has 3 and I change to 4 it should say total = 4 but it says 3 4 = 7 and it's wrong because the 4 replaced the 3 number so I wonder how can I fix my code to do that?

Thanks

CodePudding user response:

You're getting this issue because handleBlur is being called every time any of the fields is being blurred. This means that when you blur the same field you're still adding the number, despite this number no longer existing.

In your code:

<input type="text" @blur="handleBlur(post.amount)"  id="exampleInputEmail1" v-model="post.amount" placeholder="Ingresa el monto">

You already define the model (v-model="post.amount") which means that Vue is changing this automatically in the post object as you're modifying the field.

This also means that you don't have to pass post.amount to the blur function, but can simply call handleBlur:

<input type="text" @blur="handleBlur"  id="exampleInputEmail1" v-model="post.amount" placeholder="Ingresa el monto">

Then in your handleBlur method, you can simply iterate through your post array and sum up the different post.amount values:

handleBlur() {
    let totalAmount = 0;
    
    for (let i = 0, len = this.posts.length; i < len; i  ) {
        const post = this.posts;
        
        totalAmount  = post.amount;
    }
    
    this.total_inputs = totalAmount;
}

A shorter way of writing this is to simply use Array.reduce() like so:

handleBlur() {
    this.total_inputs = this.posts.reduce((totalAmount, post) => totalAmount   post.amount, 0);
}

Both of these pieces of code are doing the exact same thing.

  • Related