Vue實現手機計算器
阿新 • • 發佈:2020-08-18
本文例項為大家分享了Vue製作仿手機計算器的具體程式碼,供大家參考,具體內容如下
1.首先是把樣式做出來,按鈕是0-9,還有加減乘除,百分號,清除按鈕,小數點,等號、等等
2.把官方網站的JS外掛引用,cn.vuejs.org/v2/guide/
頁面檢視
JS
new Vue({ el: "#app",data: { equation: '0',isDecimalAdded: false,//防止在一組數字中間輸入超過一個小數位 isOperatorAdded: false,//判斷之否已點選 加、減、乘、除,防止連續點選超過一個運算子號 isStarted: false,//判斷計算器是否已經開始輸入數字,用於正負數和百分比計算的時候作一些判斷 },methods: { //Check if the character is + - × ÷ isOperator(character) { //用來判斷character 是否加減乘除 return ['+','-','×','÷'].indexOf(character) > -1 },append(character) { //append(character)加減乘除 if (this.equation === '0' && !this.isOperator(character)) { if (character === '.') { this.equation += '' + character this.isDecimalAdded = true } else { this.equation = '' + character } this.isStarted = true return } if (!this.isOperator(character)) { if (character === '.' && this.isDecimalAdded) { return } if (character === '.') { this.isDecimalAdded = true this.isOperatorAdded = true } else { this.isOperatorAdded = false } this.equation += '' + character } if (this.isOperator(character) && !this.isOperatorAdded) { this.equation += '' + character this.isDecimalAdded = false this.isOperatorAdded = true } },calculate() { //等於號的時候 let result = this.equation.replace(new RegExp('×','g'),'*').replace(new RegExp('÷','/') this.equation = parseFloat(eval(result).toFixed(9)).toString() this.isDecimalAdded = false this.isOperatorAdded = false },calculateToggle() { //點選正負號 if (this.isOperatorAdded || !this.isStarted) { true } this.equation = this.equation + '* -1' this.calculate() },calculatePercentage() { //點選百分比 if (this.isOperatorAdded || !this.isStarted) { true } this.equation = this.equation + '* 0.01' this.calculate() },clear() { //點選AC this.equation = '0' this.isDecimalAdded = false //防止在一組數字中間輸入超過一個小數位 this.isOperatorAdded = false //判斷之否已點選 加、減、乘、除,防止連續點選超過一個運算子號 this.isStarted = false //判斷計算器是否已經開始輸入數字,用於正負數和百分比計算的時候作一些判斷 } } })
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。