使用vue写一个计算器
时间: 2023-09-08 22:08:52 浏览: 82
好的,下面是使用Vue写的简单计算器示例代码:
```html
<div id="app">
<h2>Vue计算器</h2>
<div class="calculator">
<input type="text" v-model="result" />
<div class="row">
<button v-on:click="addNumber('7')">7</button>
<button v-on:click="addNumber('8')">8</button>
<button v-on:click="addNumber('9')">9</button>
<button v-on:click="addOperator('+')">+</button>
</div>
<div class="row">
<button v-on:click="addNumber('4')">4</button>
<button v-on:click="addNumber('5')">5</button>
<button v-on:click="addNumber('6')">6</button>
<button v-on:click="addOperator('-')">-</button>
</div>
<div class="row">
<button v-on:click="addNumber('1')">1</button>
<button v-on:click="addNumber('2')">2</button>
<button v-on:click="addNumber('3')">3</button>
<button v-on:click="addOperator('*')">*</button>
</div>
<div class="row">
<button v-on:click="addNumber('0')">0</button>
<button v-on:click="addOperator('/')">/</button>
<button v-on:click="calculate()">=</button>
<button v-on:click="clear()">C</button>
</div>
</div>
</div>
```
```javascript
var app = new Vue({
el: '#app',
data: {
result: '',
operator: '',
operand1: '',
operand2: '',
computed: false
},
methods: {
addNumber: function(num) {
if (this.computed) {
this.clear();
}
this.result += num;
if (this.operator === '') {
this.operand1 += num;
} else {
this.operand2 += num;
}
},
addOperator: function(op) {
if (this.operator === '') {
this.operator = op;
} else {
this.calculate();
this.operator = op;
}
},
calculate: function() {
var num1 = parseFloat(this.operand1);
var num2 = parseFloat(this.operand2);
if (this.operator === '+') {
this.result = num1 + num2;
}
if (this.operator === '-') {
this.result = num1 - num2;
}
if (this.operator === '*') {
this.result = num1 * num2;
}
if (this.operator === '/') {
this.result = num1 / num2;
}
this.operator = '';
this.operand1 = this.result;
this.operand2 = '';
this.computed = true;
},
clear: function() {
this.result = '';
this.operator = '';
this.operand1 = '';
this.operand2 = '';
this.computed = false;
}
}
});
```
这个计算器具有基本的加减乘除功能,可以在Vue的帮助下快速地实现。当用户点击数字按钮时,将数字追加到结果字符串中,并将其添加到操作数1或操作数2中,具体取决于当前操作符是什么。当用户点击操作符按钮时,如果当前没有操作符,则将其设置为所选操作符,否则先计算结果,然后将操作符设置为所选操作符。最后,当用户点击等于号时,计算结果并将其显示在结果框中。当用户点击C按钮时,清除所有的操作数和操作符,以及结果字符串。
阅读全文