vue实现计算器
Vue实现计算器的步骤
创建Vue项目
使用Vue CLI创建一个新项目,确保安装了Vue 3和相关的依赖项。可以通过以下命令初始化项目:
vue create calculator
设计计算器界面
在src/App.vue中设计计算器的界面,包括数字按钮、操作符按钮和显示区域。可以使用HTML和CSS进行布局。

<template>
<div class="calculator">
<div class="display">{{ currentValue }}</div>
<div class="buttons">
<button @click="clear">C</button>
<button @click="append('7')">7</button>
<button @click="append('8')">8</button>
<button @click="append('9')">9</button>
<button @click="append('+')">+</button>
<button @click="append('4')">4</button>
<button @click="append('5')">5</button>
<button @click="append('6')">6</button>
<button @click="append('-')">-</button>
<button @click="append('1')">1</button>
<button @click="append('2')">2</button>
<button @click="append('3')">3</button>
<button @click="append('*')">*</button>
<button @click="append('0')">0</button>
<button @click="append('.')">.</button>
<button @click="calculate">=</button>
<button @click="append('/')">/</button>
</div>
</div>
</template>
添加样式
在App.vue中添加CSS样式,使计算器看起来更美观。
<style>
.calculator {
width: 300px;
margin: 0 auto;
padding: 20px;
background-color: #f5f5f5;
border-radius: 10px;
}
.display {
width: 100%;
height: 50px;
margin-bottom: 10px;
padding: 10px;
background-color: #fff;
border: 1px solid #ddd;
border-radius: 5px;
text-align: right;
font-size: 24px;
}
.buttons {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 10px;
}
button {
height: 50px;
font-size: 18px;
border: none;
border-radius: 5px;
background-color: #e0e0e0;
cursor: pointer;
}
button:hover {
background-color: #d0d0d0;
}
</style>
实现计算逻辑
在App.vue的script部分添加计算逻辑,包括数字输入、操作符处理和计算结果。

<script>
export default {
data() {
return {
currentValue: '0',
previousValue: null,
operation: null,
resetDisplay: false
}
},
methods: {
append(number) {
if (this.resetDisplay) {
this.currentValue = '';
this.resetDisplay = false;
}
if (number === '.' && this.currentValue.includes('.')) return;
this.currentValue = this.currentValue === '0' ? number : this.currentValue + number;
},
clear() {
this.currentValue = '0';
this.previousValue = null;
this.operation = null;
},
setOperation(op) {
if (this.operation) this.calculate();
this.operation = op;
this.previousValue = this.currentValue;
this.resetDisplay = true;
},
calculate() {
if (!this.operation || !this.previousValue) return;
const prev = parseFloat(this.previousValue);
const current = parseFloat(this.currentValue);
let result;
switch (this.operation) {
case '+':
result = prev + current;
break;
case '-':
result = prev - current;
break;
case '*':
result = prev * current;
break;
case '/':
result = prev / current;
break;
default:
return;
}
this.currentValue = result.toString();
this.operation = null;
this.previousValue = null;
this.resetDisplay = true;
}
}
}
</script>
运行项目
通过以下命令启动开发服务器,查看计算器的运行效果。
npm run serve
功能扩展
如果需要更复杂的功能,可以添加以下特性:
- 支持括号运算
- 添加历史记录功能
- 实现科学计算器功能(如三角函数、对数等)
通过以上步骤,一个基本的Vue计算器就完成了。可以根据需求进一步优化界面和功能。






