用VUE帮我写一个计算器
时间: 2023-08-28 07:40:15 浏览: 92
好的,下面是一个简单的计算器的Vue代码,包含了加减乘除四则运算和清空功能:
```html
<template>
<div class="calculator">
<div class="display">{{ display }}</div>
<div class="buttons">
<button v-for="button in buttons" :key="button" @click="handleClick(button)">{{ button }}</button>
</div>
</div>
</template>
<script>
export default {
data() {
return {
display: '0',
previousOperator: null,
buffer: '0',
operatorClicked: false,
buttons: ['C', '←', '/', '7', '8', '9', '*', '4', '5', '6', '-', '1', '2', '3', '+', '0', '.', '='],
};
},
methods: {
handleClick(button) {
if (button === 'C') {
this.display = '0';
this.previousOperator = null;
this.buffer = '0';
this.operatorClicked = false;
} else if (button === '←') {
this.display = this.display.slice(0, -1) || '0';
} else if (['+', '-', '*', '/'].includes(button)) {
if (this.previousOperator && !this.operatorClicked) {
this.calculate();
}
this.previousOperator = button;
this.buffer = this.display;
this.operatorClicked = true;
} else if (button === '=') {
this.calculate();
this.previousOperator = null;
this.operatorClicked = false;
} else {
if (this.operatorClicked) {
this.display = '0';
}
this.display = this.display === '0' ? button : this.display + button;
this.operatorClicked = false;
}
},
calculate() {
let result;
const current = parseFloat(this.display);
const previous = parseFloat(this.buffer);
if (isNaN(current) || isNaN(previous)) {
return;
}
switch (this.previousOperator) {
case '+':
result = previous + current;
break;
case '-':
result = previous - current;
break;
case '*':
result = previous * current;
break;
case '/':
result = previous / current;
break;
default:
return;
}
this.display = result.toString();
},
},
};
</script>
<style scoped>
.calculator {
display: flex;
flex-direction: column;
align-items: center;
margin-top: 50px;
}
.display {
font-size: 36px;
margin-bottom: 20px;
}
.buttons {
display: grid;
grid-template-columns: repeat(4, 80px);
grid-gap: 10px;
}
button {
font-size: 24px;
padding: 10px;
border-radius: 5px;
border: none;
cursor: pointer;
background-color: #eee;
transition: background-color 0.3s;
}
button:hover {
background-color: #ddd;
}
button:active {
background-color: #ccc;
}
</style>
```
你可以将上述代码保存到一个名为 Calculator.vue 的文件中,然后在你的 Vue 应用程序中引入:
```html
<template>
<Calculator />
</template>
<script>
import Calculator from './Calculator.vue';
export default {
components: {
Calculator,
},
};
</script>
```
然后你就可以在页面上看到这个计算器了。
阅读全文