This page looks best with JavaScript enabled

Create a simple calculator using Vue from CDN

 ·   ·  ☕ 2 min read

Let us create a dead simple calculator using Vue.

Create basic structure

As it was earlier, the basic structure just has two files - index.html and main.js.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
<!-- index.html -->
<html>
  <body>
    <div id="app">
      <h1>LĂŠ Calculator</h1>
      <p>
        <input
          type="string"
          v-model="inputExpr"
          placeholder="Enter expression"
          style="width:80%;height:30px"
        />
      </p>

      <p>Result:</p>
      <p>{{ result }}</p>
    </div>
    <script src="https://unpkg.com/vue"></script>
    <script src="./main.js"></script>
  </body>
</html>

We have followed a few fundamental principles to create two elements and bind them to Vue variables - nothing new.

Create main.js -

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
new Vue({
  el: "#app",
  data() {
    return {
      inputExpr: "",
      result: ""
    };
  },
  watch: {
    inputExpr: function() {
      console.log(this.inputExpr);
      let res = "";
      try {
        res = eval(this.inputExpr);
      } catch (e) {
        res = "";
        console.error(e.message);
      }
      this.result = res;
    }
  }
});

There is only one aspect different from the earlier todo example - we have not initiated a method on button click or other event against the input box.

Instead we are watching the variable inputExpr for changes and triggering a set of actions. watch does just that - it watches for changes and triggers actions.

Save files and refresh/open index.html in your favourite browser.

vue-cdn-simple-calculator-in-action

Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things