拿vue3写一个简单的计算器
时间: 2023-10-23 20:08:47 浏览: 25
好的,以下是一个简单的计算器示例:
```
<template>
<div class="calculator">
<div class="display">{{ display }}</div>
<div class="buttons">
<button @click="press('7')">7</button>
<button @click="press('8')">8</button>
<button @click="press('9')">9</button>
<button @click="press('/')">÷</button>
<button @click="press('4')">4</button>
<button @click="press('5')">5</button>
<button @click="press('6')">6</button>
<button @click="press('*')">×</button>
<button @click="press('1')">1</button>
<button @click="press('2')">2</button>
<button @click="press('3')">3</button>
<button @click="press('-')">-</button>
<button @click="press('0')">0</button>
<button @click="press('.')">.</button>
<button @click="calculate()">=</button>
<button @click="press('+')">+</button>
</div>
</div>
</template>
<script>
export default {
data() {
return {
display: '0',
operator: null,
firstOperand: null,
waitingForSecondOperand: false
}
},
methods: {
press(key) {
if (this.display === '0') {
this.display = key
} else {
this.display += key
}
},
calculate() {
const secondOperand = parseFloat(this.display)
if (this.operator === '+') {
this.display = this.firstOperand + secondOperand
} else if (this.operator === '-') {
this.display = this.firstOperand - secondOperand
} else if (this.operator === '*') {
this.display = this.firstOperand * secondOperand
} else if (this.operator === '/') {
this.display = this.firstOperand / secondOperand
}
this.operator = null
this.firstOperand = null
this.waitingForSecondOperand = false
}
},
watch: {
display(newValue) {
if (this.waitingForSecondOperand) {
this.waitingForSecondOperand = false
} else {
if (this.operator) {
const firstOperand = parseFloat(this.firstOperand)
const secondOperand = parseFloat(newValue)
if (!isNaN(firstOperand) && !isNaN(secondOperand)) {
this.firstOperand = this.display
this.calculate()
}
} else {
this.firstOperand = newValue
}
}
}
}
}
</script>
<style>
.calculator {
width: 300px;
margin: 0 auto;
border: 1px solid #ccc;
border-radius: 3px;
padding: 20px;
}
.display {
height: 50px;
line-height: 50px;
text-align: right;
font-size: 24px;
background-color: #f5f5f5;
border: 1px solid #ccc;
border-radius: 3px;
margin-bottom: 20px;
padding: 0 10px;
}
.buttons {
display: grid;
grid-template-columns: repeat(4, 1fr);
grid-gap: 10px;
}
button {
height: 50px;
line-height: 50px;
font-size: 18px;
border: none;
border-radius: 3px;
background-color: #eee;
cursor: pointer;
}
button:hover {
background-color: #ddd;
}
</style>
```
这个计算器有四个基本运算符(加、减、乘、除),可以进行两个数的简单运算。