vue 计算器复杂组件
时间: 2023-07-01 10:04:58 浏览: 195
Vue.js实现立体计算器
以下是一个较为复杂的 Vue 计算器组件示例,它可以进行基本的加减乘除运算,还支持使用括号进行多重运算。代码如下:
```html
<template>
<div class="calculator">
<div class="display">{{ display }}</div>
<div class="buttons">
<div class="row">
<button @click="buttonClick('(')">(
<button @click="buttonClick(')')">)
<button @click="buttonClick('CE')">CE
<button @click="buttonClick('C')">C
</div>
<div class="row">
<button @click="buttonClick('7')">7
<button @click="buttonClick('8')">8
<button @click="buttonClick('9')">9
<button @click="buttonClick('/')">/
</div>
<div class="row">
<button @click="buttonClick('4')">4
<button @click="buttonClick('5')">5
<button @click="buttonClick('6')">6
<button @click="buttonClick('*')">*</button>
</div>
<div class="row">
<button @click="buttonClick('1')">1
<button @click="buttonClick('2')">2
<button @click="buttonClick('3')">3
<button @click="buttonClick('-')">-</button>
</div>
<div class="row">
<button @click="buttonClick('0')">0
<button @click="buttonClick('.')">.
<button @click="buttonClick('=')">=
<button @click="buttonClick('+')">+</button>
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
expression: '',
display: '0',
};
},
methods: {
buttonClick(value) {
switch (value) {
case 'CE':
this.expression = this.expression.slice(0, -1);
break;
case 'C':
this.expression = '';
this.display = '0';
break;
case '=':
try {
this.display = eval(this.expression).toString();
this.expression = '';
} catch (e) {
this.display = 'Error';
}
break;
default:
this.expression += value;
break;
}
if (this.expression === '') {
this.display = '0';
} else {
this.display = this.expression;
}
},
},
};
</script>
<style>
.calculator {
width: 300px;
height: 400px;
background-color: #fff;
border-radius: 5px;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
font-size: 24px;
color: #333;
}
.display {
width: 90%;
height: 70px;
margin-bottom: 20px;
display: flex;
align-items: center;
justify-content: flex-end;
padding: 0 20px;
border-radius: 5px;
background-color: #f7f7f7;
font-size: 36px;
font-weight: bold;
}
.buttons {
width: 90%;
}
.row {
display: flex;
justify-content: space-between;
margin-bottom: 10px;
}
button {
width: 70px;
height: 70px;
border: none;
border-radius: 5px;
background-color: #eee;
font-size: 24px;
font-weight: bold;
color: #333;
cursor: pointer;
}
button:hover {
background-color: #ddd;
}
</style>
```
这个计算器组件包含一个 `display` 显示框和一个按钮区域,按钮区域包含多个数字按钮和运算符按钮。点击按钮后,会根据不同的按钮值来执行不同的操作。其中,CE 按钮用于删除最后一个字符,C 按钮用于清空表达式,= 按钮用于计算表达式并显示结果,其他按钮则将对应的值添加到表达式中。计算过程中,使用 `eval()` 函数进行计算,如果表达式不合法则显示错误信息。
阅读全文