uniapp 微信小程序开发时 要求输入框只能输入3位小数,在测试时,发现小数点竟然可以多次输入,所以小数点也要限制,只能输入1个小数点才可以。代码记录,方便以后翻阅。
使用
<inputFilterDot @confirm="getPrice" :value.sync='item.Number'></inputFilterDot>
组件代码
/**
* @Author: 858834013@qq.com
* @Name: inputFilter
* @Date: 2022-07-20
* @Desc: 输入框过滤器只能输入小数点后三位
*/
<template>
<input @input="checkNum" v-model="valueNext" type="digit" placeholder="请填写"
placeholder-style="font-size:32rpx;color: #D5D5E0;" />
</template>
<script>
export default {
data() {
return {
valueNext: ''
}
},
props: {
value: {
type: String,
default () {
return '';
}
},
},
watch: {
value() {
var that = this;
setTimeout(() => {
that.$emit("update:value", that.getNumber(that.value));
that.$emit('confirm', that.getNumber(that.value))
that.valueNext = that.getNumber(that.value)
that.$forceUpdate()
}, 10)
},
},
mounted() {
var that = this;
that.valueNext = that.getNumber(that.value)
},
methods: {
getNumber(value) {
var that = this;
var num = value
if (num.indexOf(".") == 0) {
//‘首位小数点情况‘
num = num.replace(/[^$#$]/g, "0.");
num = num.replace(/\.{3,}/g, ".");
} else if (!(/^(\d?)+(\.\d{0,3})?$/.test(num))) {
var dot = String(num).indexOf(".")
num = String(num).substring(0, dot + 4);
}
return num
},
checkNum: function(event) {
var that = this;
var num = this.getNumber(event.detail.value)
setTimeout(() => {
that.$emit("update:value", num);
that.$emit('confirm', num)
that.valueNext = num
that.$forceUpdate()
}, 10)
},
}
}
</script>
<style scoped lang="scss">
</style>