Vue.js Calculator Tutorial
This Vue.js Calculator Tutorial teaches you how to create a basic calculator in Vue.js, a popular JavaScript framework that simplifies building interactive interfaces. We will explain the Vue.js Composition API, a powerful feature that allows for better code organization and reuse, and explore how Vue’s reactive elements make your web applications dynamic and responsive. This tutorial guides you through the Vue.js framework, starting with an introduction to its core concepts and leading you through setting up your first Vue.js application. Finally, we will guide you in building the calculator. The calculator is a perfect practical example to understand Vue.js in action.
Vue.js Calculator Tutorial: Introduction
Front-end development often relies on frameworks, bundles of JavaScript libraries that ease your life in building websites, web apps, or mobile apps. One of the most popular JavaScript frameworks is Vue.js. Vue.js is a Progressive Javascript Framework. Being a ‘Progressive Javascript Framework’, Vue.js boasts adaptive and versatile design. This flexibility makes Vue.js an ideal choice of front-end JavaScript for both small projects and large-scale applications.
Starting with a simple project like a calculator is a great way to get familiar with a new framework. In Vue.js, the calculator’s functionalties are handled on the client-side, showcasing the framework’s capability for creating interactive web applications. Throughout this tutorial, we will focus specifically on the Composition API, a set of features introduced in Vue 3 that enables developers to use reactive state and other features outside of the traditional Options API. This API is particularly useful for organizing code logically and managing state effectively, which is crucial for dynamic applications.
By the end of this tutorial, you’ll understand the basics principles of the Vue.js framework, the advantages of using the Composition API, and how to implement reactive elements to make web applications interactive. Let’s start our Vue.js journey by building the calculator!
Installation
Before installing Vue.js, make sure to install the latest versions of Node.js and npm on your computer. NPM is esesential for running and managing npm packages, including Vue.js. Install Node.js on a Unix-based system with this command:
sudo apt install nodejs
On Windows you can find the latest version of Node.js here. After downloading and installing Node.js. You can open a terminal on Windows, by pressing the buttons: Windows key + R. The next steps will be the same for all operating systems.
After installation, verify the versions of Node.js and npm:
node -v
npm -v
If necessary, update npm to be the latest version. You can compare the output of the command above with the version numbers of the latest version. The current version (LTS) of Node.js can be found here, and the latest version of npm here. To command to update npm to its latest version:
sudo npm install npm@latest -g
Now that we have the npm package manager installed to acquire JavaScript libraries, including Vue.js, we can install our first Vue.js project. Do so by acquiring the latest version of Vue.js
npm create vue@latest
Give your project a name. For this project, let’s say we name our project: vue-js-calculator. For the next steps, you can choose No for all shown options. Once the project is created, navigate into your new Vue.js project directory and install the necessary dependencies:
cd vue-js-calculator
npm install
After the installation completes, run the Vue.js application in developer mode by running:
npm run dev
This command launches the application in a development-optimized mode, featuring live-reloading to view changes made directly in your browser. Furthermore, all exception traces can be read as well. If all went well you should see the following message:
VITE v5.0.11 ready in 233 ms
-> Local: http://localhost:5173/
-> Network: use --host to expose
-> press h + enter to show help
Now you can visit the following page in your browser http://localhost:5173. You should be able to view the following content:

Congratulations! You now have your first Vue.js application up and running. Letβs move on to coding our calculator!
Vue.js Calculator Tutorial: Create the calulator!
First, let’s have a look at the entry point of any Vue.js application. The main.js file:
import './assets/main.css'
import { createApp } from 'vue'
import App from './App.vue'
createApp(App).mount('#app')
The main.js file imports the main app component, App.vue, and loads it into the DOM. You can see that the script binds the main App to a div with id: app. The index.html, which serves as the website’s starting point, includes the main.js script.
Now, let’s focus on the App.vue file; the starting point of our Vue.js code. The file already contains some lines to serve the demo application. Let’s remove all lines and make sure it looks like this:
<script setup>
import TheCalculator from './components/TheCalculator.vue'
</script>
<template>
<main>
<TheCalculator/>
</main>
</template>
:root {
--calculator-background-color: #1b1c1e;
--background-color: #1b1c1e;
--main-color: #323335;
--obz-green: #227a34;
}
Note: You can find all the lines of code in our GitHub project.
In App.Vue, import a single component: TheCalculator. TheCalculator components contains all elements and logic of our calculator. The styling in the :root defines CSS variables for consisting re-use of colors within the styling of the application.
Now, we have to create the TheCalculator.vue file. It should reside in the src/components directory. The component consists of three different parts.
TheCalculator.Vue: template
this part defines the layout. Parts of the layout are: the buttons to display and the displaying area for the calculation. We used Most of the code here consists of plain HTML. However, You can display variables defined in the Script section can be dispayed using {{}}, such as {{calcVal}}.
Furthermore, we can see the following snippet:
<div class="calculator-buttons col-3" v-for="btn in buttons" :key="idx">
This is a for-loop. The div is displayed n-times. Where n-being the length of the buttons array. You can also see the :class attribute within the button element:
:class="{'bg-obz-green': ['C', '*', '/', '+', '-', '=', '%'].includes(btn)}"
The meaning of this part is that the button acquires the “bg-obz-green” class whenever the value is within one of the symbols. Thus, only the numbers and the decimal sign: . are not green.
TheCalculator.Vue: script
this part of the file contains the logic necessary to make the calculations. The script contains two functions, buttonPress and calculate. The buttonPress function runs every time a user hits a button on the front-end. The calculation runs whenever a user hits the = button on the front-end.
First, let’s check the imports. The ref functions is imported from the global vue library. The ref function is used to create a reactive reference to a variable. Whenever the program updates a variable, the DOM, containing that variable, updates as well. The ref attribute is used to mark elements in <template>, so that they can be accessed from the $refs object inside <script>. The ref attribute is reactive, meaning that whenever changes are made to a reactive variable, they will be shown right away. The calcValue is marked here. The use of Decimal.js ensures precise arithmetic operations, crucial for calculator functionality. If you do not use the Decimal.js library and try to calculate:
0.2 *6
The output will be 1.2000000000000002, whereas the output should be 1.2.
The buttonPress function handles a user pressing one of the buttons. You can see the function below:
const buttonPress = (btn) => {
if (!isNaN(btn) || btn === '.') {
calcVal.value += btn.toString() + '';
} else {
switch (btn) {
case 'C':
calcVal.value = '';
break;
case '%':
calcVal.value = (calcVal.value / 100).toString() + '';
break;
case '+':
case '-':
case '*':
case '/':
operators = btn;
prevCalcVal = calcVal.value;
calcVal.value = '';
break;
case '=':
try {
calcVal.value = calculate(operators, prevCalcVal, calcVal.value);
} catch (e) {
calcVal.value = "Error";
}
prevCalcVal = ''
operators = null;
break;
default:
calcVal.value = "Invalid";
}
}
}
The function actively checks which button the user presses and responds accordingly. It calls the calculate function when the user hits the = button. You can see the function below:
const calculate = (operator, prevValue, currentValue) => {
let result = 0;
if (prevValue === "Invalid expression" || prevValue === "Division by Zero") {
prevValue = 0;
}
if (isNaN(prevValue) || prevValue === "") {
return "Invalid expression";
}
prevValue = new Decimal(prevValue);
currentValue = new Decimal(currentValue);
switch (operator) {
case '+':
result = prevValue.plus(currentValue);
break;
case '-':
result = prevValue.minus(currentValue);
break;
case '*':
result = prevValue.times(currentValue);
break;
case '/':
if (currentValue.equals(0)) {
return "Division by Zero";
}
result = prevValue.dividedBy(currentValue);
break;
case '%':
result = prevValue.mod(currentValue);
break;
default:
return "Invalid expression";
}
return result.toString();
}
The function verifies the validity of all the calculations. For instance, an expression has to have a starting number, nothing divided by something should not return an actual value. Therefore, the system ensures that prevValue is a valid number. This is also the reason why a the initial value of the calculator is 0. For both the prevValue and the currentValue we will use the Decimal object for calculations. Using these variables and the operator we can perform the calculations. The function always returns a String.
TheCalculator.Vue: style
this part contains the CSS styling of the component. You can see that we use the CSS variables for the background colors.
The complete calculator looks like this:

You can view the final version of the code here. Also, check out the live version of the calculator https://onlineblogzone.github.io/vue-calculator/. This live demo will give you a real feel of how the calculator works, and the code repository offers insight into the project structure and coding patterns used.
Vue.js Calculator Tutorial: Conclusion
Congratulations! You’ve just built a basic calculator using Vue.js. You got familiar with not only the basic concepts of Vue.js, but also got hands-on experience. By building the calculator, you’ve learned about the Composition API, reactive elements, and client-side handling in Vue.js. These three components are the key to developing dynamic web applications using Vue.js. We hope this tutorial helped you in becoming a better front-end developer. If you want us to build a specific Vue.js example application, please let us know in the comments below or by filling in this form. Happy coding!