×

vue每日一学:实现简单的计算器功能

作者:andy0012023.01.19来源:Web前端之家浏览:2510评论:0
关键词:vue

vue每日一学:实现简单的计算器功能。

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

<!DOCTYPE html>
<html>
 <head>
 <meta charset="UTF-8">
 <title>vue每日一学:实现简单的计算器功能 | Web前端之家www.jiangweishan.com</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>
 <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.10/vue.min.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>
 </body>
</html>

不过在最后我使用了一个swith循环来设置这个,还有另一种方法,代码量更少:
可以把里面的循环改成:

//这是投机取巧,不要经常用 正是开发中,尽量少用
var codeStr='parseInt(this.n1)'+this.opt+'parseInt(this.n2)'
this.result=eval(codeStr)

试试吧!

您的支持是我们创作的动力!
温馨提示:本文作者系 ,经Web前端之家编辑修改或补充,转载请注明出处和本文链接:
https://jiangweishan.com/article/vuejs20230119a23.html

网友评论文明上网理性发言 已有0人参与

发表评论: