Blogger Information
Blog 63
fans 8
comment 8
visits 50366
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
PHP大牛成长之路:使用VUE的watch属性监听实现简单计算器
周Sir-BLOG
Original
784 people have browsed it

使用VUE的watch属性监听实现简单计算器

效果图如下:

代码如下:

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8" />
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  6. <title>使用VUE的watch属性监听实现简单计算</title>
  7. <script src="vue.js"></script>
  8. </head>
  9. <body>
  10. <p>简单计算器</p>
  11. <div class="app">
  12. <input type="number" v-model="num1" />
  13. <select v-model="calculate">
  14. <option>+</option>
  15. <option>-</option>
  16. <option>*</optionb>
  17. <option>/</option>
  18. </select>
  19. <input type="number" v-model="num2" /> =
  20. <input type="number" v-model="res" disabled />
  21. </div>
  22. <script>
  23. const app = new Vue({
  24. el: ".app",
  25. data: {
  26. num1: 0,
  27. num2: 0,
  28. res: 0,
  29. calculate:'+'
  30. },
  31. methods: {
  32. // 获取运算符进行相应计算
  33. cal(){
  34. switch(this.calculate){
  35. case '+':
  36. return parseFloat(this.num1) + parseFloat(this.num2);
  37. break;
  38. case '-':
  39. return parseFloat(this.num1) - parseFloat(this.num2);
  40. break;
  41. case '*':
  42. return parseFloat(this.num1) * parseFloat(this.num2);
  43. break;
  44. case '/':
  45. return parseFloat(this.num1) / parseFloat(this.num2);
  46. break;
  47. }
  48. },
  49. },
  50. // watch监听器
  51. watch: {
  52. // 监听第1个input变化
  53. num1(newVol,oldVol){
  54. this.res = this.cal(newVol,this.num2);
  55. },
  56. // 监听第2个input变化
  57. num2(newVol,oldVol){
  58. this.res = this.cal(newVol,this.num1);
  59. },
  60. // 监听第运算符变化
  61. calculate(newVol,oldVol){
  62. this.res = this.cal(newVol,this.num1);
  63. }
  64. }
  65. });
  66. </script>
  67. </body>
  68. </html>

总结:

  • 虽然很简单做出来了,但感觉代码太冗余。
Correcting teacher:天蓬老师天蓬老师

Correction status:qualified

Teacher's comments:代码冗余没关系的, 做对才重要
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post