1. 程式人生 > 程式設計 >vue.js實現簡單的計算器功能

vue.js實現簡單的計算器功能

使用vue.js來編寫一個簡單的計算器,供大家參考,具體內容如下

效果如圖所示:是一個十分簡單的計算器,包含了加減乘除,不是用原生js寫的,而是用vue.js寫的

vue.js實現簡單的計算器功能

html:

<!DOCTYPE html>
<html>
 <head>
 <meta charset="UTF-8">
 <title></title>
 </head>
 <body>
 <div id="app">
  
  <input type="text" v-model="n1" />
  <select v-model="opt">
  <option value="+">+</option>
  <option value="-">-</option>
  <option value="*">*</option>
  <option value="/">/</option>
  </select>
  
  <input type="text" v-model="n2" />
  <input type="button" value="=" @click="calc" />
  <input type="text" v-model="result" />
 </div>

 </body>
</html>

js程式碼:

<script src="js/vue.js"></script>
 <script>
  var vm=new Vue({
  el:"#app",data:{
   n1:0,n2:0,result:0,opt:"+"
  },methods:{
   //定義計算器算數的方法
   calc(){
   switch(this.opt){
    case "+":
    this.result=parseInt(this.n1)+parseInt(this.n2)
    //return this.result
    break;
    case "-":
    this.result=parseInt(this.n1)-parseInt(this.n2)
    //return this.result
    break;
    case "*":
    this.result=parseInt(this.n1)*parseInt(this.n2)
    //return this.result
    break;
    case "/":
    this.result=parseInt(this.n1)/parseInt(this.n2)
    //return this.result
    break;
   }
   
   }
  }
  })
</script>

不過在最後我使用了一個swith迴圈來設定這個,還有另一種方法,程式碼量更少:
可以把裡面的迴圈改成:

//這是投機取巧,不要經常用 正是開發中,儘量少用
var codeStr='parseInt(this.n1)'+this.opt+'parseInt(this.n2)'
this.result=eval(codeStr)

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。