要用Vue.js写一个简单的计算器,需要以下几个步骤:
-
构建UI界面:使用HTML和CSS构建一个基本的UI界面,包含数字键、运算符键、结果显示框等。
-
定义数据:定义data属性,存储计算器中的当前表达式和结果。
-
实现方法:定义methods属性,实现计算器中的各种操作方法,如加、减、乘、除等。
-
绑定事件:使用v-on指令绑定事件,使得按键可以触发对应的方法。
-
更新显示:使用v-model指令绑定结果显示框,当操作完成后,更新结果值并将其显示在结果显示框中。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Calculator</title>
<!-- 引入CSS文件 -->
<link rel="stylesheet" href="calculator.css">
</head>
<body>
<!-- 计算器主体部分 -->
<div id="app">
<div class="calculator">
<div class="display">{{ result }}</div>
<div class="keys">
<button v-for="key in keys" v-on:click="calculate(key)">{{ key }}</button>
</div>
</div>
</div>
<!-- 引入Vue.js库 -->
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<!-- 引入JavaScript文件 -->
<script src="calculator.js"></script>
</body>
</html>
/* 样式表 */
.calculator {
background-color: #fff;
border: 1px solid #ccc;
border-radius: 5px;
box-shadow: 0px 2px 4px rgba(0, 0, 0, 0.2);
width: 200px;
margin: 50px auto;
}
.display {
background-color: #f5f5f5;
padding: 10px;
text-align: right;
font-size: 24px;
height: 40px;
}
.keys {
display: flex;
flex-wrap: wrap;
justify-content: space-between;
align-items: center;
padding: 10px;
}
button {
border: none;
background-color: #f5f5f5;
padding: 10px;
font-size: 18px;
width: 40px;
height: 40px;
border-radius: 5px;
margin: 5px;
cursor: pointer;
}
button:hover {
background-color: #ccc;
}
// JavaScript代码
new Vue({
el: '#app',
data: {
expression: '',
result: 0,
keys: ['7', '8', '9', '+', '4', '5', '6', '-', '1', '2', '3', '*', '0', '.', '=', '/']
},
methods: {
calculate(key) {
if (key === '=') {
this.result = eval(this.expression);
this.expression = '';
} else if (key === 'C') {
this.expression = '';
this.result = 0;
} else {
this.expression += key;
}
}
}
})