日期: 2020-06-22 17:43:53
使用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)
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持奥多码。