背景
由于要还原微信转账时的数字键盘,组件库里的 keyboard不太满足我的需求,就自己实现了个。
在输入时也做了限制如:
- 输入 "01" - "09" 的字符串时,赋值时会自动 去除前面的 0
- 输入 "00" 时,赋值时 自动 转为 "0"
- 限制小数点个数,不能连续输入 多个小数点
- 限制小数个数只有两位
效果图
键盘代码如下
<!-- 键盘 -->
<view class="keyboard-wrap">
<view class="keyboard-left">
<view
:class="{'w_370': index === 9, 'w_normal': index !== 9}"
class="keyboard-item key-item-h"
hover-class="u-hover-class bg-gray"
:hover-stay-time="100"
@click="() => handleChange(getKeyValue(item,index))"
v-for="(item,index) in 11" :key="index">
<template v-if="item <= 9">
{
{ index=== 9 ? 0 : index+1}}
</template>
<template v-else>.</template>
</view>
</view>
<view class="keyboard-actions">
<view class="keyboard-item w_normal key-item-h"
hover-class="u-hover-class bg-gray"
:hover-stay-time="100"
@click="handleKeyboardBackspace">
<u-icon name="close" size="28"></u-icon>
</view>
<view
class="keyboard-item w_normal key-submit"
hover-class="u-hover-class bg-gray"
:hover-stay-time="100">
转账
</view>
</view>
</view>
<script>
export default {
data() {
priceValue: ""
},
methods: {
getKeyValue(index) {
if (index === 10) {
return '.'; // 当 index 等于 10 时,返回 '.'
} else if (index === 9) {
return 0; // 当 index 等于 9 时,返回 0
} else {
return index + 1; // 其他情况,返回 index + 1
}
},
handleChange(val) {
// 将 priceValue 转换为字符串以进行操作
let priceValueStr = this.priceValue.toString();
// 检查是否是小数点
if (val === '.') {
// 如果当前字符串中还没有小数点,则添加小数点
if (!priceValueStr.includes('.')) {
priceValueStr += val;
}
// 如果已经包含小数点,不再添加小数点
} else {
// 如果是数字,检查是否已经存在小数点
if (priceValueStr.includes('.')) {
// 获取小数点后的长度
let decimalPart = priceValueStr.split('.')[1];
// 如果小数点后的长度已经达到2位,则不再添加数字
if (decimalPart && decimalPart.length >= 2) {
return; // 阻止添加更多的数字
}
// 如果小数点后长度未达到2位,则添加数字
priceValueStr += val;
} else {
// 如果还没有小数点,添加数字
priceValueStr += val;
}
}
// 去掉 '01' 到 '09' 前面的 '0'
if (val !== '0' && priceValueStr.length > 1 && priceValueStr[0] === '0' && priceValueStr[1] !== '.') {
priceValueStr = priceValueStr.substring(1);
}
// 更新 priceValue
this.priceValue = priceValueStr;
},
// 删除
handleKeyboardBackspace() {
if(this.priceValue.length) this.priceValue = this.priceValue.substr(0,
this.priceValue.length - 1);
},
}
}
</script>
<style lang="scss">
.keyboard-wrap {
display: flex;
padding: 10rpx;
.keyboard-left {
width: 80%;
display: flex;
flex-wrap: wrap;
justify-content: space-around;
}
.w_370 {
width: 358rpx;
}
.w_normal {
width: 170rpx;
}
.key-item-h {
height: 90rpx;
}
.keyboard-actions {
.key-submit {
margin-top: 8px;
background: #07c160;
color: #fff;
height: 156px;
}
}
.keyboard-item {
background-color: #fff;
display: flex;
flex-direction: row;
justify-content: center;
align-items: center;
border-radius: 8px;
margin: 8rpx 4rpx;
font-weight: bold;
font-size: 32rpx;
}
.bg-gray {
background: #bbbcc6;
}
}
</style>