Vue+Element 計算器2

效果:
在這裏插入圖片描述

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章