黑馬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>
