VueJS: Building A Simple Calculator

in VueJS

In previous tutorials of VueJS we've learnt the basics of how to use Vue, but we haven't really learning how to build an application.

In this tutorial we're going to learn how to create our first application a VueJS calculator.

calculator

We're going to be using some of the techniques learnt in previous tutorials including:

  • User inputs
  • Click events
  • Computed properties
  • Vue Components

First we start off by adding the HTML to the page.

<div id="app">
    <h1>Calculator</h1>
    <calculator></calculator>
</div>

As you can see all we have on the page is a title and a single calculator tag this is because we're going to build the calculator by using Vue components. This allows you to just print the calculator tag anywhere on the page to display the calculator.

Calculator Button Component

As we're going to have a lot of buttons on the calculator to be used for numbers and operators we're going to create a reuseable component for the button.

First create the Vue component using the Vue.component method.

Vue.component('calculator-button', { });

The template used on this component is just going to be a button.

var calculator_button = Vue.component('calculator-button', {
    template:  '<button></button>'
});

The text used on the button is going to be passed in by the parent object (the calculator) using props.

var calculator_button = Vue.component('calculator-button', {
    template:  '<button>{{ this.text }}</button>',
    props: {
        text: '',
    }
});

Calculator Component

First we start off by adding the HTML for the calculator, we will need a textbox to show the clicked numbers, 10 buttons with the numbers 0 - 9, the 4 operators of add, subtract, multiple and divide, a clear button and a equal button.

var calculator = Vue.component('calculator', {
    template: '<div class="calculator">' +
            '<p><input type="text" v-model="displayContents" readonly /></p>' +
            '<div class="numbers"><calculator-button v-for="n in 10" v-bind:text="n-1" v-on:click.native="addToSum(n-1)"></calculator-button></div>' +
            '<div class="conditions">' +
            '<calculator-button text="+" v-on:click.native="addition"></calculator-button>' +
            '<calculator-button text="-" v-on:click.native="subtract"></calculator-button>' +
            '<calculator-button text="*" v-on:click.native="multiple"></calculator-button>' +
            '<calculator-button text="/" v-on:click.native="divide"></calculator-button>' +
            '</div> ' +
            '<div class="equals">' +
            '<calculator-button text="C" v-on:click.native="clear"></calculator-button>' +
            '<calculator-button text="=" v-on:click.native="sum"></calculator-button>' +
            '</div>' +
            '</div>'
    ,
});

The textbox has a v-model which is being linked to a displayContent data property on the calculator object. It also has a readonly attribute to make sure that the user has to click on the buttons to enter the numbers into the calculator.

Then we have the numbers div which uses the calculator-button component inside. The calculator-button needs to show the numbers 0 - 9 we do this by using a for loop from n in 10. It expects a prop of text to be passed in for the number on the button this is done with the v-bind directive v-bind:text="n-1". There needs to be a click event on the button to add the number to the calculator, as it has the same functionality we're going to use a method of addToSum passing in the number on the calculator v-on:click.native="addToSum(n-1)". You'll notice there is a .native on the end of the click event, this tells Vue to the method lives on object which defines the click event this being the calculator instead of the button.

Then we add the condition buttons which are for add, subtract, multiple and divide. We're going to use the same calculator-button, passing in the correct text and assigning the method for the click event.

After these we add 2 more buttons the clear button and the equals button. These buttons also need to use the text prop to add the content of the button and run the click event for the button.

Data Properties

With the template in place we need to add the data property to the calculator, for this we're going to use the following:

  • sumContents - An array storing the numbers and operators making up the sum
  • answer - The answer for the sum
  • answered - If the equal button has been clicked, allowing us to block people clicking equal multiple times
data: function () {
        return {
            sumContents: [],
            answer: '',
            answered: false
        };
    },

Methods

All the methods in the application are used on the click events of the buttons.

The first method is the addToSum method, which is used to add the content to the array of the sumContents data property, we take in a parameter and push this parameter into the sumContents array.

addToSum: function(number)
{
    if(this.answered)
    {
        return;
    }

    this.sumContents.push(number);
}
[javascript]

The operators are going to be added to the sumContents as we can construct the sum from this array so on each call to these methods we add the contents to the sum.

[javascript]
addition: function()
{
    this.addToSum(' + ');
}
subtract: function()
{
   this.addToSum(' - ');
},
multiple: function()
{
   this.addToSum(' * ');
},
divide: function()
{
   this.addToSum(' / ');
},

The sum function is ran when we click the equals button on the calculator. From this we build a string from the array of sumContents then we can eval that string to calculate the answer to the sum. Once we have the answer we can add this to the sumContents array as this is used to display the sum in the textbox.

sum: function()
        {
            try
            {
                for (var i in this.sumContents) {
                    this.answer += this.sumContents[i];
                }

                this.answer = eval(this.answer);

                this.sumContents.push(' = ');
                this.sumContents.push(this.answer);

                this.answered = true;
            }
            catch(er)
            {

            }
        },

The clear button needs to simply reset the data points to the default.

clear: function()
        {
            this.sumContents = [];
            this.answer = '';
            this.answered = false;
        }

To display the contents of the sum in the textbox we use a computed function to take the sumContents and change it into a string.

computed:
{
    displayContents: function(){
        return this.sumContents.join('');
    }
}

Below is the entire contents of the calculator object.

var calculator = Vue.component('calculator', {
    template: '<div class="calculator">' +
            '<p><input type="text" v-model="displayContents" readonly /></p>' +
            '<div class="numbers"><calculator-button v-for="n in 10" v-bind:text="n-1" v-on:click.native="addToSum(n-1)"></calculator-button></div>' +
            '<div class="conditions">' +
            '<calculator-button text="+" v-on:click.native="addition"></calculator-button>' +
            '<calculator-button text="-" v-on:click.native="subtract"></calculator-button>' +
            '<calculator-button text="*" v-on:click.native="multiple"></calculator-button>' +
            '<calculator-button text="/" v-on:click.native="divide"></calculator-button>' +
            '</div> ' +
            '<div class="equals">' +
            '<calculator-button text="C" v-on:click.native="clear"></calculator-button>' +
            '<calculator-button text="=" v-on:click.native="sum"></calculator-button>' +
            '</div>' +
            '</div>'
    ,
    data: function () {
        return {
            sumContents: [],
            answer: '',
            answered: false
        };
    },
    methods:
    {
        addToSum: function(number)
        {
            if(this.answered)
            {
                return;
            }

            this.sumContents.push(number);
        },
        addition: function()
        {
            this.addToSum(' + ');
        },
        subtract: function()
        {
            this.addToSum(' - ');
        },
        multiple: function()
        {
            this.addToSum(' * ');
        },
        divide: function()
        {
            this.addToSum(' / ');
        },
        sum: function()
        {
            try
            {
                for (var i in this.sumContents) {
                    this.answer += this.sumContents[i];
                }

                this.answer = eval(this.answer);

                this.sumContents.push(' = ');
                this.sumContents.push(this.answer);

                this.answered = true;
            }
            catch(er)
            {

            }
        },
        clear: function()
        {
            this.sumContents = [];
            this.answer = '';
            this.answered = false;
        }
    },
    computed:
    {
        displayContents: function(){
            return this.sumContents.join('');
        }
    }
});

Now with the calculator build we can start Vue by creating the Vue object.

var app = new Vue({
    el: '#app',
})

View the demo to see what we've just created and how it all works.

Demo

You can also click the download button below to get the entire contents of this tutorial.

Any questions please comment below.

Upgrade to access all content on Paulund

Members unlock all tutorials and snippets

Access to all downloadable content

Access to code examples before others

Sign Up Now

Already a member? Login here

Subscribe To Newsletter

Get weekly updates to your email