给我写一个微信小程序开发计算器案例完整代码
时间: 2024-10-02 09:00:40 浏览: 104
微信小程序的计算器是一个基础的小程序功能示例,这里提供一个简单的加减乘除功能的代码:
```html
<!-- app.json -->
{
"pages": [
"index",
"login",
"settings"
],
"window": {
"backgroundTextStyle": "light",
"navigationBarBackgroundColor": "#fff",
"navigationBarTitleText": "Wechat Calculator",
"navigationBarTextStyle": "black"
}
}
<!-- index.wxml -->
<view class="container">
<button bindtap="clear">清空</button>
<view class="calculator" wx:for="{{numbers}}" wx:key="*this">{{item}}</view>
<input type="number" value="{{result}}" placeholder="请输入计算结果" />
<button bindtap="add">+</button>
<button bindtap="subtract">-</button>
<button bindtap="multiply">*</button>
<button bindtap="divide">/</button>
<button bindtap="calculate">=</button>
</view>
<!-- index.wxss -->
.container {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
.calculator {
flex-direction: column;
margin-bottom: 5px;
}
<!-- index.js -->
Page({
data: {
numbers: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'],
result: '',
operation: ''
},
methods: {
clear() {
this.setData({
numbers: [],
result: '',
operation: ''
});
},
add() {
if (this.data.operation === '+') {
let sum = parseFloat(this.data.result) + parseFloat(numbers[this.data.numbers.length - 1]);
this.setData({
numbers: [...this.data.numbers, sum],
result: sum.toString(),
operation: ''
});
} else {
this.setData({
numbers: [this.data.result, ...this.data.numbers],
result: '',
operation: '+'
});
}
},
subtract() { ... },
multiply() { ... },
divide() { ... },
calculate() { ... },
// 其他运算方法类似,只是处理除法时需要防止除数为零
}
})
```
这个代码展示了基本的界面结构和事件绑定,实际开发中还需要完善错误处理、输入验证等细节,并根据需求添加更多的运算操作。注意,在微信小程序开发环境中运行此代码。
阅读全文