Open In App

Build a Calculator with VueJS

We'll learn how to build a simple calculator app using Vue.js. A calculator is a fundamental tool for performing mathematical calculations, and building one using Vue.js is a great way to understand the basics of Vue.js components, data binding, and event handling.

Step-by-step guide to set up the project

Step 1: Install Vue CLI Globally

npm install -g @vue/cli

Step 2: Create a New Vue.js Project

vue create vue-calculator

Step 3: Navigate to your project directory

cd vue-calculator

Project Structure:

Screenshot-2024-04-23-214010

Step 4: Install Required Dependencies

npm install axios

Step 5: Changing the files

Example: This example shows the calculator using VueJs.

/*Calculator.css*/

#app {
    font-family: Arial, sans-serif;
    text-align: center;
    margin-top: 40px;
  }
  .title {
    color: green;
  }
  
  .calculator {
    width: 300px;
    margin: 0 auto;
    border: 1px solid #ccc;
    border-radius: 5px;
    padding: 20px;
  }
  
  .result {
    width: 90%;
    padding: 10px;
    font-size: 20px;
    text-align: right;
    margin-bottom: 10px;
  }
  
  .buttons {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    grid-gap: 10px;
  }
  
  button {
    padding: 15px;
    font-size: 18px;
    cursor: pointer;
    border: none;
    outline: none;
  }
  
  .number, .operator {
    background-color: #f0f0f0;
  }
  
  .clear, .equal {
    background-color: #ff6666;
    color: #fff;
  }
  
  button:hover {
    background-color: #ddd;
  }
  
  .equal {
    grid-column: span 2;
  }
  
//App.vue

<template>
  <div id="app">
    <h1 class="title">GeeksForGeeks</h1>
    <h2>Calculator App</h2>
    <div class="calculator">
      <input type="text" class="result"
               :value="result" readonly />
      <div class="buttons">
        <button class="number" 
                @click="handleClick('7')">7</button>
        <button class="number"
                @click="handleClick('8')">8</button>
        <button class="number"
                @click="handleClick('9')">9</button>
        <button class="operator"
                @click="handleOperatorClick('/')">/</button>

        <button class="number"
                @click="handleClick('4')">4</button>
        <button class="number" 
                @click="handleClick('5')">5</button>
        <button class="number"
                @click="handleClick('6')">6</button>
        <button class="operator"
                @click="handleOperatorClick('*')">*</button>

        <button class="number"
                @click="handleClick('1')">1</button>
        <button class="number"
                @click="handleClick('2')">2</button>
        <button class="number" 
                @click="handleClick('3')">3</button>
        <button class="operator"
                @click="handleOperatorClick('-')">-</button>

        <button class="number"
                @click="handleClick('0')">0</button>
        <button class="number"
                @click="handleClick('.')">.</button>
        <button class="number" 
                @click="handleClick('00')">00</button>

        <button class="operator" 
                @click="handleOperatorClick('+')">+</button>

        <button class="clear"
                @click="handleClear">C</button>
        <button class="clear"
                @click="handleClearEntry">CE</button>
        <button class="equal"
                @click="calculate()">=</button>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'App',
  data() {
    return {
      result: '',
      calculated: false
      // Flag to track if calculation has been done
    };
  },
  methods: {
    handleClick(value) {
      if (this.calculated) {
        // If calculation has been done, 
        // start a new expression
        this.result = value;
        this.calculated = false; // Reset flag
      } else {
        this.result += value;
      }
    },
    handleClear() {
      this.result = '';
      this.calculated = false; // Reset flag
    },
    handleClearEntry() {
      if (this.result && this.result.length > 0) {
        this.result = this.result.slice(0, -1);
        if (this.result.length === 0) {
          this.handleClear();
        }
      } else {
        this.handleClear();
      }
    },
    handleOperatorClick(operator) {
      // If the last character is an operator, 
      // replace it with the new operator
      if (/[+*/-]$/.test(this.result)) {
        this.result = this.result.slice(0, -1) + operator;
      } else {
        // Otherwise, add the new operator
        this.result += operator;
      }
      this.calculated = false; // Reset flag
    },
    calculate() {
      try {
        let evaluatedResult = eval(this.result.
            replace(/(^|[^0-9])0+(\d+)/g, '$1$2'));
        if (evaluatedResult === Infinity ||
            evaluatedResult === -Infinity) {
          throw new Error('Divide by zero error');
        }
        this.result = Number.isFinite(evaluatedResult)
                      ? evaluatedResult : 'Error';
        this.calculated = true;
        // Set flag to true after calculation
      } catch (error) {
        if (error.message === 'Divide by zero error') {
          this.result = 'Error: Divide by zero';
        } else {
          this.result = 'Error';
        }
      }
    }
  }
};
</script>

<style src="./Calculator.css">
/* Add your styles here */
</style>
//main.js

 // Import createApp from Vue
import { createApp } from 'vue';
import App from './App.vue';

// Create a Vue app instance
const app = createApp(App);

// Mount the app to the DOM
app.mount('#app');

Steps to run the Application:

npm run serve

Visit http://localhost:8080 in your browser to see the Vue Calculator app running.

Output:

cc

Article Tags :