1

I am trying to add up an Object.value, having its adding value bound to the number being inputed in my input through a v-model to total number.

When I input any number then use the @click listener the behaviour is odd, it keeps concatenating whatever I am firing, treating the result as a String instead of a Number.

Interesting that if I comment out the input tag, hence removing the v-model and changing the value on this.shared[2].value to any number greater then 0, the desired behaviour will occur.

<template>
  <div>
    <input type="number" v-model="shares[2].value">
    <p>{{this.shares[0].value}}</p>
    <button class="btn btn-primary"
            @click="result">Sum An Object Value</button>
  </div>
</template>

<script>

  export default {
    data(){
      return {
        shares: [
          {id: 'BMW', value: 0},
          {id: 'Ford', value: 0},
          {id:'Apple', value: 0}
        ]
      }
    },
    methods: {
      result(){
        this.shares[0].value += this.shares[2].value
      }
    }
  }
</script>

How could I get the appropriate behaviour here?

0

1 Answer 1

1

From the Vue docs:

If you want user input to be automatically typecast as a number, you can add the number modifier to your v-model managed inputs:

<input v-model.number="age" type="number">

This is often useful, because even with type="number", the value of HTML input elements always returns a string. If the value cannot be parsed with parseFloat(), then the original value is returned.

Sign up to request clarification or add additional context in comments.

1 Comment

thanks for this refresher. I have been studying vue and its overwhelming sometimes, specially when I forget this details after modules and plus modules of contents =)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.