vue model Implementation of Simple Calculator

  • 2021-08-06 20:41:14
  • OfStack

In this paper, we share the specific code of vue-model to realize simple calculator for your reference. The specific contents are as follows


<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <meta http-equiv="X-UA-Compatible" content="ie=edge">
 <title>Vue</title>
 <script src="../lib/vue-2.4.0.js"></script>
</head>
<body>
 
 <div id="app" >
  <!--  Figures 1 -->
  <input type="text" v-model='n1' placeholder="0">
  <!--  Addition, subtraction, multiplication and division  -->
  <select v-model='opt'>
   <option value="+"> + </option>
   <option value="-">-</option>
   <option value="*">*</option>
   <option value="/">/</option>
  </select>
  <!--  Figures 2 -->
  <input type="text" v-model='n2' placeholder="0">
  <!--  Equal sign  -->
  <input type="button" value='=' >
  <!--  Results  -->
  <input type="text" v-model='result' placeholder="0">
  <!--  OK button  -->
  <input type="button" value=' Results ' @click='calc'>
  <!--  Return to zero  -->
  <input type="button" value=' Return to zero ' @click='zero'>


 </div>

 <script>
  var vm = new Vue({
   el: '#app', // Represents the current new This instance of controls which area on the page 
   data: { //data Attribute holds the  el  Data to be used in 
    n1: '',
    n2:'',
    result:'',
    opt: '+'
   },
   methods:{
    calc(){
     // switch(this.opt){
     //  case '+':
     //  this.result = parseInt(this.n1) + parseInt(this.n2)
     //  break;
     //  case '-':
     //  this.result = parseInt(this.n1) - parseInt(this.n2)
     //  break;
     //  case '*':
     //  this.result = parseInt(this.n1) * parseInt(this.n2)
     //  break;
     //  case '/':
     //  this.result = parseInt(this.n1) / parseInt(this.n2)
     //  break;
     // }

     //  Abbreviation 
     var codeStr = 'parseInt(this.n1) '+ this.opt +' parseInt(this.n2)'
     this.result = eval(codeStr)
    },
    zero(){
     this.n1 = '',
     this.n2 = '',
     this.result = '',
     this.opt = '+'
    }

   }
  }) 
 </script>

</body>
</html>

For technical articles about calculators, please click on the topic: javascript Calculator Function Summary


Related articles: