服务器之家:专注于服务器技术及软件下载分享
分类导航

node.js|vue.js|jquery|angularjs|React|json|js教程|

服务器之家 - 编程语言 - JavaScript - Vue实现手机计算器

Vue实现手机计算器

2021-08-24 16:39昵称~ JavaScript

这篇文章主要为大家详细介绍了Vue实现手机计算器,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

本文实例为大家分享了Vue制作仿手机计算器的具体代码,供大家参考,具体内容如下

1.首先是把样式做出来,按钮是0-9,还有加减乘除,百分号,清除按钮,小数点,等号、等等

Vue实现手机计算器

2.把官方网站的JS插件引用,cn.vuejs.org/v2/guide/

Vue实现手机计算器

页面视图

Vue实现手机计算器

JS

Vue实现手机计算器

Vue实现手机计算器

Vue实现手机计算器

  1. new Vue({
  2. el: "#app",
  3. data: {
  4. equation: '0',
  5. isDecimalAdded: false, //防止在一组数字中间输入超过一个小数位
  6. isOperatorAdded: false, //判断之否已点击 加、减、乘、除,防止连续点击超过一个运算符号
  7. isStarted: false, //判断计算器是否已经开始输入数字,用于正负数和百分比计算的时候作一些判断
  8. },
  9. methods: {
  10. //Check if the character is + - × ÷
  11. isOperator(character) { //用来判断character 是否加减乘除
  12. return ['+', '-', '×', '÷'].indexOf(character) > -1
  13. },
  14. append(character) { //append(character)加减乘除
  15. if (this.equation === '0' && !this.isOperator(character)) {
  16. if (character === '.') {
  17. this.equation += '' + character
  18. this.isDecimalAdded = true
  19. } else {
  20. this.equation = '' + character
  21. }
  22. this.isStarted = true
  23. return
  24. }
  25.  
  26. if (!this.isOperator(character)) {
  27. if (character === '.' && this.isDecimalAdded) {
  28. return
  29. }
  30.  
  31. if (character === '.') {
  32. this.isDecimalAdded = true
  33. this.isOperatorAdded = true
  34. } else {
  35. this.isOperatorAdded = false
  36. }
  37. this.equation += '' + character
  38. }
  39.  
  40. if (this.isOperator(character) && !this.isOperatorAdded) {
  41. this.equation += '' + character
  42. this.isDecimalAdded = false
  43. this.isOperatorAdded = true
  44. }
  45. },
  46. calculate() { //等于号的时候
  47. let result = this.equation.replace(new RegExp('×', 'g'), '*').replace(new RegExp('÷', 'g'), '/')
  48. this.equation = parseFloat(eval(result).toFixed(9)).toString()
  49. this.isDecimalAdded = false
  50. this.isOperatorAdded = false
  51. },
  52. calculateToggle() { //点击正负号
  53. if (this.isOperatorAdded || !this.isStarted) {
  54. true
  55. }
  56.  
  57. this.equation = this.equation + '* -1'
  58. this.calculate()
  59. },
  60. calculatePercentage() { //点击百分比
  61. if (this.isOperatorAdded || !this.isStarted) {
  62. true
  63. }
  64.  
  65. this.equation = this.equation + '* 0.01'
  66. this.calculate()
  67. },
  68. clear() { //点击AC
  69. this.equation = '0'
  70. this.isDecimalAdded = false //防止在一组数字中间输入超过一个小数位
  71. this.isOperatorAdded = false //判断之否已点击 加、减、乘、除,防止连续点击超过一个运算符号
  72. this.isStarted = false //判断计算器是否已经开始输入数字,用于正负数和百分比计算的时候作一些判断
  73. }
  74. }
  75. })

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

原文链接:https://blog.csdn.net/qq_42577408/article/details/108039240

延伸 · 阅读

精彩推荐