设计一个vue计算器代码
时间: 2024-10-17 09:03:00 浏览: 26
设计一个Vue.js计算器的基本步骤包括创建组件、处理用户输入和计算结果。下面是一个简单的Vue组件示例,它允许用户添加数字、运算符,并显示最终的结果:
```html
<template>
<div class="calculator">
<input type="text" v-model.number="display" readonly />
<div class="buttons">
<!-- 数字按钮 -->
<button @click="appendNumber(num)" :key="num" v-for="(num, index) in numbers">{{ num }}</button>
<!-- 运算符按钮 -->
<button @click="operator = operator === '' ? num : '+'">{{ num }}</button>
<button @click="calculate">=</button>
<button @click="clearDisplay">C</button>
</div>
<p>当前操作:{{ operator }}</p>
</div>
</template>
<script>
export default {
data() {
return {
display: '',
operator: '', // 空字符串初始
numbers: ['7', '8', '9', '/', '4', '5', '6', '*', '1', '2', '3', '-', '0', '.'],
};
},
methods: {
appendNumber(num) {
this.display += num;
},
clearDisplay() {
this.display = '';
this.operator = '';
},
calculate() {
if (this.operator !== '') {
let result;
switch (this.operator) {
case '+':
result = parseFloat(this.display) + parseFloat(this.lastNumber);
break;
case '-':
result = parseFloat(this.display) - parseFloat(this.lastNumber);
break;
case '*':
result = parseFloat(this.display) * parseFloat(this.lastNumber);
break;
case '/':
result = parseFloat(this.display) / parseFloat(this.lastNumber);
break;
}
this.display = result.toFixed(2); // 保留两位小数
this.operator = '';
this.lastNumber = '';
}
},
},
computed: {
lastNumber() {
return this.display.slice(-1);
},
},
};
</script>
<style scoped>
.calculator {
/* 样式省略 */
}
</style>
```
在这个例子中,`v-model.number`用于双向绑定数字输入框,`@click`事件监听按钮点击,`switch`语句负责执行相应的计算操作。
阅读全文