【知识分享】vue制作一个页面计算器

1.制作思路

制作一个简单的页面计算器可以分为以下几个步骤:

(1)创建 Vue 组件,包括显示屏和按钮组件。

(2)设置数据属性,用于存储计算器的当前状态(如显示屏上的数字)。

(3)编写方法,实现计算器的基本功能(加减乘除等)。

(4)在模板中使用按钮组件,并绑定点击事件调用对应的方法。

2.具体代码

<template>
  <div class="calculator">
    <div class="screen">{{ display }}</div>
    <div class="buttons">
      <button @click="appendToDisplay('7')">7</button>
      <button @click="appendToDisplay('8')">8</button>
      <!-- 其他数字按钮 -->
      <button @click="calculate()">=</button>
      <button @click="clear()">C</button>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      display: '0',
      currentInput: '',
      operator: null,
      result: null
    };
  },
  methods: {
    appendToDisplay(value) {
      if (this.display === '0' || this.result !== null) {
        this.display = value;
        this.result = null;
      } else {
        this.display += value;
      }
      this.currentInput += value;
    },
    clear() {
      this.display = '0';
      this.currentInput = '';
      this.operator = null;
      this.result = null;
    },
    calculate() {
      if (this.operator && this.currentInput !== '') {
        this.result = eval(this.display);
        this.display = this.result.toString();
        this.currentInput = this.result.toString();
        this.operator = null;
      }
    }
  }
};
</script>

<style>
.calculator {
  width: 200px;
  margin: 0 auto;
}

.screen {
  height: 40px;
  background-color: #f0f0f0;
  text-align: right;
  padding: 10px;
  font-size: 20px;
}

.buttons {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
}

button {
  height: 50px;
  line-height: 50px;
  text-align: center;
  border: 1px solid #ccc;
}
</style>
注意:这是一个简单的四则运算计算器示例,包含数字按钮、清空按钮和等号按钮。你可以根据需要扩展功能,比如添加更多运算符、支持小数点、处理错误输入等。

  • 24
    点赞
  • 31
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

加瓦程序设计师

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值