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 -->
    <div id="app">
      <h1>Lé Calculator</h1>
          placeholder="Enter expression"

      <p>{{ result }}</p>
    <script src=""></script>
    <script src="./main.js"></script>

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() {
      let res = "";
      try {
        res = eval(this.inputExpr);
      } catch (e) {
        res = "";
      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.


comments powered by Disqus