工作记录
最最近在做 uniapp 开发的移动端 H5 页面,有个需求是金额输入框只能输入数字,不能输入小数点和其他字符,经过各种尝试,发现其他字符可以通过正则过滤掉,但是输入小数点的话,因为没有触发 @input 和 watch 事件,导致没法过滤掉,最后只能通过自定义键盘的形式解决,详细代码如下:
<template>
<view>
<view class="container" @click="hideKeyboardFunc">
<view class="flex" @click.stop="showKeyboard('num')">
<view :style="num?'width: 100%;color':'width: 100%;color:#aeb3bb'">{{num||'请输入金额'}}</view>
<span>元</span>
</view>
</view>
<!-- 自定义键盘 -->
<view class="keyboard" v-show="keyboard">
<button v-for="(item, index) in 9" :key="index" @click.stop="key(index + 1)">
<text>{{ index + 1 }}</text>
</button>
<button @click="hideKeyboardFunc" class="hide" style="font-size:20px">关闭</button>
<button @click.stop="key(0)">
<text>0</text>
</button>
<button @click.stop="del()">
<text style="font-size:20px">删除</text>
</button>
</view>
</view>
</template>
<script>
export default {
data() {
return {
num:'', // 金额字段
currentKey:'', // 当前点击的输入框的字段名,适用于输入框有多的的情况
keyboard:false
};
},
methods: {
// 吊起键盘
showKeyboard(key){
this.keyboard = true
this.currentKey = key
},
// 拼接输入的内容
key(key) {
this[this.currentKey] += key+''
},
// 删除输入框中的内容
del() {
const str = this[this.currentKey]+''
if (str.length > 0) {
this[this.currentKey] = str.substring(0, str.length - 1)
}
},
// 隐藏键盘
hideKeyboardFunc(){
this.keyboard=false
}
},
};
</script>
<style lang="scss">
.container{
width: 100%;
height: 100vh;
padding: 15px;
background-color: #ffffff;
}
.flex{
display: flex;
padding: 15px;
border: 1px solid #ccc;
}
.keyboard {
position: fixed;
bottom: 0;
width: 100%;
background: #EEEEEE;
display: flex;
flex-wrap: wrap;
justify-content: space-between;
z-index: 999;
button {
display: flex;
align-items: center;
justify-content: center;
width: calc(100vw / 3 - 1rpx);
background: #FFFFFF;
border-radius: 0;
margin-top: 1rpx;
font-size: 50rpx;
height: 120rpx;
&.button-hover:not(.hide) {
background: #EEEEEE;
}
image {
width: 52rpx;
height: 38rpx;
}
}
}
</style>
效果如图: