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

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

效果如图所示:是一个十分简单的计算器,包含了加减乘除,不是用原生js写的,而是用vue.js写的

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

html:

<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> </head> <body> <div> <input type="text" v-model="n1" /> <select v-model="opt"> <option value="+">+</option> <option value="-">-</option> <option value="*">*</option> <option value="https://www.jb51.net/">/</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="https://www.jb51.net/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 "https://www.jb51.net/": 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)

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/dc7b6cf4111b2ac0260e5263c733ab56.html