使用Vue實現簡單計算器
阿新 • • 發佈:2020-02-26
使用Vue編寫簡單計算器,供大家參考,具體內容如下
在Vue中,v-model 指令,可以實現表單元素和 Model 中資料的雙向資料繫結,接下來,我們就用這個指令編寫一個簡單的計算器,程式碼如下
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> </head> <body> <!--計算器的顯示結構--> <div id="app"> <input type="text" v-model="n1"> <select v-model="opt"> <option value="+">+</option> <option value="-">-</option> <option value="*">*</option> <option value="/">/</option> </select> <input type="text" v-model="n2"> <input type="button" value="=" @click="calculator"> <input type="text" v-model="result"> </div> <script> // 建立 Vue 例項,得到 ViewModel,簡寫vm var vm = new Vue({ el: '#app',data: { n1: 0,n2: 0,opt: '+',result: 0 },methods: { //計算的方法 calculator() { switch (this.opt) { case '+': this.result = Number(this.n1) + Number(this.n2); break; case '-': this.result = Number(this.n1) - Number(this.n2); break; case '*': this.result = Number(this.n1) * Number(this.n2); break; case '/': this.result = Number(this.n1) / Number(this.n2); break; } } } }); </script> </body> </html>
執行結果如下:
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。