帮我写一个Vue3的计算器案列
时间: 2023-08-13 21:07:32 浏览: 95
好的,下面是一个简单的Vue3计算器案例:
```
<template>
<div class="calculator">
<div class="display">{{ result }}</div>
<div class="buttons">
<button v-for="button in buttons" :key="button" @click="handleClick(button)">{{ button }}</button>
</div>
</div>
</template>
<script>
import { ref, computed } from 'vue';
export default {
name: 'Calculator',
setup() {
const result = ref('0');
const buttons = ['AC', '+/-', '%', '/', '7', '8', '9', '*', '4', '5', '6', '-', '1', '2', '3', '+', '0', '.', '='];
const handleClick = (button) => {
switch (button) {
case 'AC':
result.value = '0';
break;
case '+/-':
result.value = result.value.charAt(0) === '-' ? result.value.slice(1) : `-${result.value}`;
break;
case '%':
result.value = `${parseFloat(result.value) / 100}`;
break;
case '=':
result.value = `${eval(result.value)}`;
break;
default:
if (result.value === '0') {
result.value = button;
} else {
result.value += button;
}
}
};
const displayResult = computed(() => {
return parseFloat(result.value).toLocaleString();
});
return {
result: displayResult,
buttons,
handleClick,
};
},
};
</script>
<style>
.calculator {
width: 300px;
margin: 0 auto;
text-align: center;
background-color: #f5f5f5;
}
.display {
height: 60px;
line-height: 60px;
font-size: 36px;
font-weight: bold;
background-color: #fff;
border-bottom: 1px solid #ccc;
}
.buttons {
display: flex;
flex-wrap: wrap;
margin: 10px;
}
button {
width: 60px;
height: 60px;
margin: 5px;
font-size: 24px;
font-weight: bold;
background-color: #fff;
border-radius: 50%;
border: 1px solid #ccc;
cursor: pointer;
}
button:hover {
background-color: #ccc;
}
</style>
```
这个计算器实现了简单的加、减、乘、除、百分号等操作,使用了Vue3的`ref`和`computed`,并且使用了`setup`函数来实现组件。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044901.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)