Vue实现简易计算器

刺骨的言语ヽ痛彻心扉 2022-10-23 08:16 283阅读 0赞

文章目录

  • 简易计算器案例
      1. HTML 代码结构
      1. Vue实例代码:
      1. 全部代码

简易计算器案例

在这里插入图片描述

1. HTML 代码结构

  1. <div id="app">
  2. <input type="text" v-model="n1">
  3. <select v-model="opt">
  4. <option value="+">+</option>
  5. <option value="-">-</option>
  6. <option value="*">*</option>
  7. <option value="/">/</option>
  8. </select>
  9. <input type="text" v-model="n2">
  10. <input type="button" value="=" @click="calc">
  11. <input type="text" v-model="result">
  12. </div>

2. Vue实例代码:

  1. // 创建 Vue 实例,得到 ViewModel
  2. var vm = new Vue({
  3. el: '#app',
  4. data: {
  5. n1: 0,
  6. n2: 0,
  7. result: 0,
  8. opt: '+'
  9. },
  10. methods: {
  11. calc() { // 计算器算数的方法
  12. // 逻辑:
  13. switch (this.opt) {
  14. case '+':
  15. this.result = parseInt(this.n1) + parseInt(this.n2)
  16. break;
  17. case '-':
  18. this.result = parseInt(this.n1) - parseInt(this.n2)
  19. break;
  20. case '*':
  21. this.result = parseInt(this.n1) * parseInt(this.n2)
  22. break;
  23. case '/':
  24. this.result = parseInt(this.n1) / parseInt(this.n2)
  25. break;
  26. }
  27. // 注意:这是投机取巧的方式,正式开发中,尽量少用
  28. // var codeStr = 'parseInt(this.n1) ' + this.opt + ' parseInt(this.n2)'
  29. // this.result = eval(codeStr)
  30. }
  31. }
  32. });

3. 全部代码

  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. <meta http-equiv="X-UA-Compatible" content="ie=edge">
  7. <title>Document</title>
  8. <script src="./lib/vue-2.4.0.js"></script>
  9. </head>
  10. <body>
  11. <div id="app">
  12. <input type="text" v-model="n1">
  13. <select v-model="opt">
  14. <option value="+">+</option>
  15. <option value="-">-</option>
  16. <option value="*">*</option>
  17. <option value="/">/</option>
  18. </select>
  19. <input type="text" v-model="n2">
  20. <input type="button" value="=" @click="calc">
  21. <input type="text" v-model="result">
  22. </div>
  23. <script> // 创建 Vue 实例,得到 ViewModel 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) break; case '-': this.result = parseInt(this.n1) - parseInt(this.n2) break; case '*': this.result = parseInt(this.n1) * parseInt(this.n2) breakvalue_name: value, case '/': this.result = parseInt(this.n1) / parseInt(this.n2) break; } // 注意:这是投机取巧的方式,正式开发中,尽量少用 // var codeStr = 'parseInt(this.n1) ' + this.opt + ' parseInt(this.n2)' // this.result = eval(codeStr) } } }); </script>
  24. </body>
  25. </html>

发表评论

表情:
评论列表 (有 0 条评论,283人围观)

还没有评论,来说两句吧...

相关阅读