使用vue编写一个简单的计算器
时间: 2023-08-02 16:08:40 浏览: 95
好的,下面是使用Vue编写的简单计算器:
HTML部分:
```html
<div id="app">
<div class="calculator">
<input type="text" v-model="display" disabled>
<div class="buttons">
<button @click="addNumber(7)">7</button>
<button @click="addNumber(8)">8</button>
<<button @click="addNumber(9)">9</button>
<<button @click="addOperator('+')">+</button>
<button @click="addNumber(4)">4</button>
<button @click="addNumber(5)">5</button>
<button @click="addNumber(6)">6</button>
<button @click="addOperator('-')">-</button>
<button @click="addNumber(1)">1</button>
<button @click="addNumber(2)">2</button>
<button @click="addNumber(3)">3</button>
<button @click="addOperator('*')">*</button>
<button @click="addNumber(0)">0</button>
<button @click="addDecimal()">.</button>
<button @click="calculate()">=</button>
<button @click="addOperator('/')">/</button>
<button @click="clear()">C</button>
</div>
</div>
</div>
```
CSS部分:
```css
.calculator {
width: 300px;
margin: auto;
text-align: center;
}
input {
width: 100%;
height: 50px;
margin-bottom: 10px;
font-size: 24px;
text-align: right;
}
button {
width: 50px;
height: 50px;
margin: 5px;
font-size: 24px;
background-color: #f0f0f0;
border-radius: 5px;
border: none;
cursor: pointer;
}
```
JavaScript部分:
```javascript
new Vue({
el: "#app",
data: {
display: "0",
operator: null,
firstNumber: null,
secondNumber: null,
result: null
},
methods: {
addNumber(number) {
if (this.display === "0") {
this.display = number.toString();
} else {
this.display += number.toString();
}
},
addDecimal() {
if (!this.display.includes(".")) {
this.display += ".";
}
},
addOperator(operator) {
this.operator = operator;
this.firstNumber = parseFloat(this.display);
this.display = "0";
},
calculate() {
this.secondNumber = parseFloat(this.display);
switch (this.operator) {
case "+":
this.result = this.firstNumber + this.secondNumber;
break;
case "-":
this.result = this.firstNumber - this.secondNumber;
break;
case "*":
this.result = this.firstNumber * this.secondNumber;
break;
case "/":
this.result = this.firstNumber / this.secondNumber;
break;
}
this.display = this.result.toString();
},
clear() {
this.display = "0";
this.operator = null;
this.firstNumber = null;
this.secondNumber = null;
this.result = null;
}
}
});
```
这是一个非常简单的计算器,只实现了加、减、乘、除四个基本运算。你可以根据需要进行扩展。
阅读全文