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>
注意:这是一个简单的四则运算计算器示例,包含数字按钮、清空按钮和等号按钮。你可以根据需要扩展功能,比如添加更多运算符、支持小数点、处理错误输入等。