JavaScript
主页 > 网络编程 > JavaScript >

详解vue.js实现简单的计算器功能

2020-02-22 | 秩名 | 点击:

使用vue.js来编写一个简单的计算器,供大家参考,具体内容如下

效果如图所示:是一个十分简单的计算器,包含了加减乘除,不是用原生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)

原文链接:https://blog.csdn.net/JTz666666/article/details/104099801?depth_1-utm_source=distribute.pc_relevant.none-task&utm_source=distribute.pc_relevant.none-task
相关文章
最新更新