用Vue.js制作一个简易的计算器

  1. 样式设计:
.calculator {
  width: 200px;
  margin: 20px auto;
  padding: 10px;
  border: 1px solid #ccc;
  text-align: center;
}

.calculator input {
  width: 100%;
  margin-bottom: 10px;
  padding: 5px;
  font-size: 20px;
  text-align: right;
}

.calculator button {
  width: 45px;
  height: 45px;
  margin: 5px;
  font-size: 20px;
}
  1. 创建 HTML 结构:
<div id="app">
  <div class="calculator">
    <input type="text" v-model="display" disabled>
    <div>
      <button @click="appendToDisplay('7')">7</button>
      <button @click="appendToDisplay('8')">8</button>
      <button @click="appendToDisplay('9')">9</button>
      <button @click="operation('/')">/</button>
    </div>
    <!-- 其他数字和运算符按钮 -->
    <div>
      <button @click="clearDisplay">C</button>
      <button @click="appendToDisplay('0')">0</button>
      <button @click="calculate">=</button>
      <button @click="operation('+')">+</button>
    </div>
  </div>
</div>

3.设置数据和方法:

data: {
  display: '', // 用于显示用户输入和计算结果
  operators: ['+', '-', '*', '/'] // 定义可用的运算符
},
methods: {
  appendToDisplay(value) {
    this.display += value; // 将用户点击的按钮值追加到显示区域
  },
  clearDisplay() {
    this.display = ''; // 清空显示区域
  },
  calculate() {
    try {
      this.display = eval(this.display); // 使用eval函数计算表达式结果
    } catch (error) {
      this.display = 'Error'; // 错误处理
    }
  },
  isOperator(value) {
    return this.operators.includes(value); // 判断输入值是否为运算符
  },
  operation(operator) {
    if (this.display !== '' && !this.isOperator(this.display.slice(-1))) {
      this.display += operator; // 如果显示区域不为空且最后一个字符不是运算符,则添加运算符
    }
  }
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值