帮我写一个Vue3计算器
时间: 2023-08-13 07:08:23 浏览: 52
好的,以下是一个简单的Vue3计算器的示例代码:
```
<template>
<div class="calculator">
<div class="screen">{{ display }}</div>
<div class="buttons">
<button v-for="btn in buttons" :key="btn" @click="handleButton(btn)">{{ btn }}</button>
</div>
</div>
</template>
<script>
import { ref } from 'vue';
export default {
name: 'Calculator',
setup() {
const display = ref('0');
const buttons = ['C', '±', '%', '/', '7', '8', '9', '*', '4', '5', '6', '-', '1', '2', '3', '+', '0', '.', '='];
const handleButton = (btn) => {
switch (btn) {
case 'C':
display.value = '0';
break;
case '±':
display.value = (parseFloat(display.value) * -1).toString();
break;
case '%':
display.value = (parseFloat(display.value) / 100).toString();
break;
case '=':
display.value = eval(display.value).toString();
break;
default:
display.value = (display.value === '0' ? btn : display.value + btn);
break;
}
};
return {
display,
buttons,
handleButton,
};
},
};
</script>
<style scoped>
.calculator {
width: 300px;
margin: 0 auto;
border: 1px solid #ccc;
border-radius: 5px;
padding: 10px;
font-size: 20px;
font-weight: bold;
text-align: right;
box-shadow: 0 0 5px rgba(0, 0, 0, 0.2);
}
.screen {
height: 50px;
line-height: 50px;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
.buttons {
display: flex;
flex-wrap: wrap;
margin-top: 10px;
}
button {
width: 50px;
height: 50px;
margin: 5px;
background-color: #eee;
border: none;
border-radius: 5px;
box-shadow: 0 0 5px rgba(0, 0, 0, 0.2);
font-size: 20px;
font-weight: bold;
cursor: pointer;
transition: background-color 0.2s ease-in-out;
}
button:hover {
background-color: #ddd;
}
</style>
```
这个计算器包含了基本的加减乘除、取反、百分比、清除等功能,并且使用了Vue3的Composition API编写。你可以在组件中引入这段代码,然后在页面中使用该组件即可。