黑马vue---15、使用v-model实现简易计算器

黑马vue---15、使用v-model实现简易计算器

一、总结

一句话总结:

用v-model绑定了第一个数,第二个数,操作符,和结果,数据改变他们跟着变,他们变数据也跟着变

select v-model="opt"

1、eval取巧方式?

this.result = eval('parseInt(this.n1) ' + this.opt + ' parseInt(this.n2)')

二、内容在总结中

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 
 4 <head>
 5   <meta charset="UTF-8">
 6   <meta name="viewport" content="width=device-width, initial-scale=1.0">
 7   <meta http-equiv="X-UA-Compatible" content="ie=edge">
 8   <title>Document</title>
 9   <script src="./lib/vue-2.4.0.js"></script>
10 </head>
11 
12 <body>
13   <div id="app">
14     <input type="text" v-model="n1">
15 
16     <select v-model="opt">
17       <option value="+">+</option>
18       <option value="-">-</option>
19       <option value="*">*</option>
20       <option value="/">/</option>
21     </select>
22 
23     <input type="text" v-model="n2">
24 
25     <input type="button" value="=" @click="calc">
26 
27     <input type="text" v-model="result">
28   </div>
29 
30   <script>
31     // 创建 Vue 实例,得到 ViewModel
32     var vm = new Vue({
33       el: '#app',
34       data: {
35         n1: 0,
36         n2: 0,
37         result: 0,
38         opt: '+'
39       },
40       methods: {
41         calc() { // 计算器算数的方法  
42           // 逻辑:
43           /* switch (this.opt) {
44             case '+':
45               this.result = parseInt(this.n1) + parseInt(this.n2)
46               break;
47             case '-':
48               this.result = parseInt(this.n1) - parseInt(this.n2)
49               break;
50             case '*':
51               this.result = parseInt(this.n1) * parseInt(this.n2)
52               break;
53             case '/':
54               this.result = parseInt(this.n1) / parseInt(this.n2)
55               break;
56           } */
57 
58           // 注意:这是投机取巧的方式,正式开发中,尽量少用
59           var codeStr = 'parseInt(this.n1) ' + this.opt + ' parseInt(this.n2)'
60           this.result = eval(codeStr)
61         }
62       }
63     });
64   </script>
65 </body>
66 
67 </html>
 
原文地址:https://www.cnblogs.com/Renyi-Fan/p/11658091.html