Home » vue » Vue 2 – how to calculate total from v-models integer values

Vue 2 – how to calculate total from v-models integer values

Posted by: admin November 26, 2021 Leave a comment

Questions:

i am using nuxt 2.8.1

i have 100 inputs. All inputs are number

i want to calculate in sum all number to get total

i tried this

computed: {
     total() {
       return this.form.one + this.form.two
     }
}

what i expected

5 + 5 = 10

what output getting

5 + 5 = 55

if i don’t put value in two
result 5null

i don’t understand why its

Answers:

It considers them like strings and concatenates them like you see, so you should use a Number object to cast them to integers like :

 return Number(this.form.one) + Number(this.form.two)

to be more efficient i recommend to use reduce function since you’re having multiple inputs :

 return Object.values(this.form).reduce((a,c)=>{
       return a+Number(c);                 
       },0)

Example :

let form = {
  one: 45,
  two: 5,
  three: 7
}

let sum = Object.values(form).reduce((a, c) => {
  return a + Number(c);
}, 0)

console.log(sum)

###

Since your param is a form, i guess this is related to user input. Then you could also solve it with a modifier (https://vuejs.org/v2/guide/forms.html#number)

HTML

<input v-model.number="form.one" ></input>
<input v-model.number="form.two" ></input>

JS (same as it was before, or with the reduce method)

computed: {
     total() {
       return this.form.one + this.form.two
     }
}