- 样式设计:
.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;
}
- 创建 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; // 如果显示区域不为空且最后一个字符不是运算符,则添加运算符
}
}
}