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>
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With