Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating numbers with vue

I am really new to vueJS.

I try to get two input value, adding them together, and show the result. I found it is really wired, because when number1 minus number3, or number1 multiplied number2, or number1 divided number2, the calculating is all working fine. However when number1 plus number2, it doesn’t working, and seems add two str together (for example: 1 + 2 = 12).

What’s going on here? And how can I get result with number1 + number2

Please help

<div id="app">

        <input type="number" name="number1" v-on:input= "update_number1">
        <p>{{ number1 }}</p>
        <input type="number" name="number2" v-on:input= "update_number2">
        <p>{{ number2 }}</p>

        <hr>
        <p>{{ result() }}</p>

</div>

new Vue({
  el: '#app',
  data: {
    number1: 0,
    number2: 0,
  },
  methods: {
    update_number1: function (event) {
      this.number1 = event.target.value;
    },
    update_number2: function (event) {
      this.number2 = event.target.value;
    },
    result: function () {

      return this.number1 + this.number2;
    },

  },
});
like image 545
Xiaozhou Song Avatar asked Feb 21 '18 12:02

Xiaozhou Song


1 Answers

This is more likely a javascript problem than a vue one.

If you want to add two numbers, you can use parseInt() function as:

result: function () {
  return parseInt(this.number1) + parseInt(this.number2);
}
like image 77
samayo Avatar answered Sep 23 '22 00:09

samayo