element-plus vue3实现计算器
时间: 2023-10-09 10:09:47 浏览: 172
以下是使用element-plus和Vue3实现的简单计算器示例:
HTML代码:
```html
<div id="app">
<el-input v-model="input" placeholder="请输入数字"></el-input>
<div class="btn-group">
<el-button @click="append('+')">+</el-button>
<el-button @click="append('-')">-</el-button>
<el-button @click="append('*')">*</el-button>
<el-button @click="append('/')">/</el-button>
<el-button @click="calculate">=</el-button>
</div>
<div class="result">{{ result }}</div>
</div>
```
JavaScript代码:
```js
import { createApp, ref } from 'vue'
import { ElInput, ElButton } from 'element-plus'
const app = createApp({
components: {
ElInput,
ElButton
},
setup() {
const input = ref('0')
const result = ref('0')
const operator = ref(null)
const resetInput = () => {
input.value = '0'
operator.value = null
}
const append = (value) => {
if (input.value === '0') {
input.value = value
} else {
input.value += value
}
}
const calculate = () => {
const a = parseFloat(result.value)
const b = parseFloat(input.value)
switch (operator.value) {
case '+':
result.value = a + b
break
case '-':
result.value = a - b
break
case '*':
result.value = a * b
break
case '/':
result.value = a / b
break
default:
result.value = input.value
}
resetInput()
}
return {
input,
result,
operator,
resetInput,
append,
calculate
}
}
})
app.mount('#app')
```
CSS代码:
```css
.btn-group {
display: flex;
margin-top: 10px;
}
.el-button {
flex: 1;
margin-right: 10px;
}
.result {
margin-top: 10px;
font-size: 24px;
}
```
效果展示:
![效果展示](https://i.loli.net/2022/01/06/8sTzJrO9oCvGKjN.png)
阅读全文