vue。js写一个计算器代码
时间: 2024-10-16 18:19:35 浏览: 29
Vue.js实现立体计算器
Vue.js是一个流行的前端框架,它专注于构建用户界面并提供组件化开发体验。下面是一个简单的Vue.js计算器应用的示例,我们创建一个基础的加减乘除功能:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Vue Calculator</title>
<script src="https://cdn.jsdelivr.net/npm/vue@2"></script>
</head>
<body>
<div id="app">
<input v-model.number="number1" placeholder="Number 1">
+
<input v-model.number="number2" placeholder="Number 2">
=
<span v-bind:class="{ result: true }">{{ result }}</span>
<br/>
<button @click="add">Add</button>
<button @click="subtract">Subtract</button>
<button @click="multiply">Multiply</button>
<button @click="divide">Divide</button>
</div>
<script>
new Vue({
el: '#app',
data: {
number1: '',
number2: '',
result: ''
},
methods: {
add() {
this.result = Number(this.number1) + Number(this.number2);
this.number1 = '';
this.number2 = '';
},
subtract() {
this.result = Number(this.number1) - Number(this.number2);
this.number1 = '';
this.number2 = '';
},
multiply() {
this.result = Number(this.number1) * Number(this.number2);
this.number1 = '';
this.number2 = '';
},
divide() {
if (this.number2 !== '') {
this.result = Number(this.number1) / Number(this.number2);
} else {
alert('Cannot divide by zero');
}
this.number1 = '';
this.number2 = '';
}
},
computed: {
// 使用计算属性处理结果的显示和清空
result() {
return Number(this.number1) || 0 + Number(this.number2) || 0;
}
}
});
</script>
</body>
</html>
```
在这个例子中,我们有四个操作按钮,每个按钮触发相应的计算方法,并将结果显示在页面上。`v-model`用于双向数据绑定输入框的值,而`computed`属性则是响应式地计算结果。
阅读全文