Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ADD numbers in vueJS

If I change the symbols at {{ num1+num2+num3 }} with symbols for multiplication (*) or substraction (-) it works well. However, when trying to add by using the (+) it simply concatenates.

    <div id="vue_mult">
    <input type="number" v-model="num1"  min="78" max="98" /> + 
    <input type="number" v-model="num2"  min="78" max="98" /> + 
    <input type="number" v-model="num3"  min="78" max="98" /> =
    {{ num1+num2+num3 }}
</div>
    <script>
    const app = new Vue({
        el:'#vue_mult',
        data: {  
            num1:0,
            num2:0,
            num3:0
        } //end data property 
    }) //end Vue object
</script>
</body>
</html>
like image 991
Carlos Dominguez Avatar asked Dec 12 '18 04:12

Carlos Dominguez


1 Answers

It's because the value of each input are automatically strings (hell, everything is a string in HTML/HTTP), therefore being concatenated by default. I would do the summation on a method (or a computed property) and convert the values to integers during the operation. This also separates some concerns -- making your template arguably cleaner.

    const app = new Vue({
        el:'#vue_mult',
        data: {  
            num1:80,
            num2:80,
            num3:80
        },
        methods: {
            sum: function(nums){
                let result = 0;
                nums.forEach(function(n){ result += n * 1; });
                return result
            }
        }
//end data property 
    }) //end Vue object
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>

    <div id="vue_mult">
    <input type="number" v-model="num1"  min="78" max="98" /> + 
    <input type="number" v-model="num2"  min="78" max="98" /> + 
    <input type="number" v-model="num3"  min="78" max="98" /> =
    {{ sum([num1, num2, num3]) }}
</div>

</body>
</html>
like image 87
Abana Clara Avatar answered Sep 20 '22 23:09

Abana Clara