How to add two numbers in VueJS?

Hi Friends đź‘‹,

Welcome To Sortoutcode! ❤️

To add two numbers in vue.js, use the + operator it will add if your value datatype is a number else if your value datatype is a string first convert it using Number() and then perform the addition operation.

In the following example, we will take the sample numbers, and strings and perform an addition operation using the + addition operator.

Adding Two numbers example

let num1 = 20;
let num2 = 25;
num2 + num1; // 45

Adding Two string numbers example

let num1 = "20";
let num2 = "25";
parseInt(num2) + parseInt(num1); // 45

Setup the Vue.js

First, we have to install the Vue project, I had installed the vueJS in my system. If you haven’t installed or have any problem with installation you can follow this article, which will show you step by step process of installation.

How to Install the VueJS project?

After the vue.js project setup, I’m going to show you How to add two numbers in vuejs, as mentioned above here, I’m going to use the + addition operator.

Let’s start today’s tutorial on how do you add two numbers in vue.js?

In this example, we will do

  • take an example of a number and string number data() function
  • Adding two numbers example
  • Adding two string numbers example
  • print the output on the page screen

FirstComponent.vue

<template>
    <div>
        <h1>Adding two numbers example</h1>
        <input type="number" v-model.number="firstNum" /> +
        <input type="number" v-model.number="secondNum" /> = 
        <span>{{ firstNum + secondNum }}</span>
        <h1>Adding two string numbers example</h1>
        <input type="number" v-model="firstStr" /> +
        <input type="number" v-model="secondStr" /> = 
        <span>{{ Number(firstStr) + Number(secondStr) }}</span>
    </div>
</template>

<script>
export default {
    name: "FirstComponent",
    data() {
        return {
            firstNum: "",
            secondNum: "",
            firstStr: "",
            secondStr: "",
        }
    }
};
</script>

In the above vue js example, we have taken the sample numbers and string numbers data(), and performed Adding two numbers example, and Adding two string numbers example.

Output

Addition in Vue.js

I hope it helps you, All the best đź‘Ť.

Follow me on Twitter