Create a simple calculator using Vue from CDN

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.

<!-- 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 -

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

comments powered by Disqus