vue写一个计算器
时间: 2023-07-01 16:10:33 浏览: 53
好的,以下是一个简单的Vue计算器代码:
```
<template>
<div class="calculator">
<div class="display">{{ display }}</div> <!-- 显示屏 -->
<div class="btn-container">
<!-- 数字按钮 -->
<button v-for="num in numbers" :key="num" @click="addToDisplay(num)">{{ num }}</button>
<!-- 运算符按钮 -->
<button v-for="operator in operators" :key="operator" @click="addToDisplay(operator)">{{ operator }}</button>
<!-- 清空按钮 -->
<button @click="clearDisplay">C</button>
<!-- 等号按钮 -->
<button @click="calculate">=</button>
</div>
</div>
</template>
<script>
export default {
data() {
return {
display: "", // 显示屏内容
numbers: ["7", "8", "9", "4", "5", "6", "1", "2", "3", "0", "."], // 数字按钮
operators: ["+", "-", "*", "/"], // 运算符按钮
};
},
methods: {
addToDisplay(value) {
this.display += value; // 将按钮内容添加到显示屏内容中
},
clearDisplay() {
this.display = ""; // 清空显示屏内容
},
calculate() {
this.display = eval(this.display); // 计算显示屏内容的结果并显示
},
},
};
</script>
<style scoped>
.calculator {
border: 1px solid #ccc;
border-radius: 5px;
padding: 10px;
width: 240px;
}
.display {
background-color: #eee;
border: none;
border-radius: 5px;
font-size: 24px;
height: 40px;
margin-bottom: 10px;
padding: 5px;
text-align: right;
width: 100%;
}
.btn-container {
display: flex;
flex-wrap: wrap;
}
button {
background-color: #fff;
border: 1px solid #ccc;
border-radius: 5px;
font-size: 18px;
height: 40px;
margin-right: 5px;
margin-bottom: 5px;
width: calc(25% - 6px);
}
button:last-child {
width: calc(50% - 6px);
}
</style>
```
在Vue中,我们可以通过绑定按钮的@click事件来实现计算器的功能。在上面的代码中,我们定义了一个display变量来保存显示屏的内容,并将数字和运算符按钮分别放在一个数组中。通过v-for指令,我们可以循环遍历这些数组来动态生成按钮。addToDisplay方法用于将按钮内容添加到显示屏内容中,clearDisplay方法用于清空显示屏内容,calculate方法用于计算显示屏内容的结果并显示。最后,我们使用CSS来美化计算器的样式。