效果:
<template>
<div>
<span>{{val}}</span>
<div>
<el-button @click="onClick(item)" v-for="item in buttonList" :key="item">{{item}}</el-button>
</div>
</div>
</template>
<script>
export default {
name: 'calculator',
data: function () {
return {
buttonList: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '-', '*', '/', '='],
val: '',
// 記錄是否剛添加完運算符的標誌
flag: false
}
},
methods: {
onClick (p) {
// 1、判斷是否爲等號
if (p === '=') {
return this.calculator()
}
// 2、判斷是否爲操作符號
if (p === '+' || p === '-' || p === '*' || p === '/') {
return this.pushOperate(p)
}
// 3、添加數字
this.pushNum(p)
},
pushNum (p) {
this.val = this.val + p
this.flag = false
},
pushOperate (o) {
// 第一位不能是運算符
if (this.val.length === 0) {
return this.$message.error('第一位不能是運算符')
}
// 如果已經輸入一個運算符,替換前一個運算符
if (this.flag) {
this.val = this.val.substring(0, this.val.length - 1)
}
this.val = this.val + o
this.flag = true
},
calculator () {
this.val = window.eval(this.val)
}
}
}
</script>