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

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

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

JTz666666   2020-05-17 我要评论

使用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)

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们