Simple Calculator Just Using Properties in Vue JS [ Beginners]

Vue.js

This article demonstrates how easy it is to create a simple calculator in Vue JS just using in the combination of regular and computed properties without using any events similar to the animation below.

In the vue template, declare four HTML elements.

  • <input> for number 1
  • <select> with four operands ( +, -, * , /) as options
  • <input> for number 2
  • <h2> for the result.
<template>
<section>
  <input placeholder="num1" type="number">
  <select > 
    <option value="+"> + </option>
    <option value="-"> - </option>
    <option value="*"> * </option>
    <option value="/"> / </option>
  </select>
  <input placeholder="num2" type="number" >
  <h2></h2>
  </section>
<template>

Then declare four properties inside this component, three inside the data() model and one will be a computed property.

<script>
    export default {
      data() {
        return {
          num1: 0,
          num2: 0,
          operand:""
        };
      },
    }
</script>

Then bind these three properties to the input fields using a v-model directive with the number modifier except the operand property.

The number modifier will cast the value of num1 and num2 properties to a number so that we do not have to convert it outside of the template.

<input placeholder="num1" type="number" v-model.number="num1">
<select v-model="operand" > 
  <option value="+"> + </option>
  <option value="-"> - </option>
  <option value="*"> * </option>
  <option value="/"> / </option>
</select>
<input placeholder="num2" type="number" v-model.number="num2">

There are multiple ways to implement the calculation, but the simplest way is to use a computed property.

Computed property is a great way to create new data from the existing properties declared in the data() model.

It also can be reactive and recompute any operation inside the computed property when any of the properties used inside have changed.

computed: {
  result() {
    switch(this.operand) {
      case "+":
        return this.num1 + this.num2
      case "-":
        return this.num1 - this.num2
      case "*":
        return this.num1 * this.num2
      case "/":
        return this.num1 / this.num2
    }
  }
}

Every time there will be data changed in the num1, num2 or operand properties, the result computed property will recalculate the num1 and num2 based on the operand and return an appropriate result.

Then we can use the result in the template.

<h2> {{result}} </h2>