input限制输入小数点后两位(vue版本)

首先想到在input事件中正则匹配一下,但是,在输入错误格式或非数字的情况下,会将整个输入框清空,体验很不好:
<template>
    <input 
        placeholder="限制小数点后两位" 
        type="text" 
        v-model="count" 
        @input="count=/^\d+\.?\d{0,2}$/.test(count)||count == '' ? count : count=''">
</template>
<script>
    data() {
        return {
            count: 0
        }
    }
</script>

 然后我就加了一个字段,在keyup事件中赋值,然后匹配

<template>
    <input 
        placeholder="限制小数点后两位" 
        type="text" v-model="count" 
        @keydown="checkKeydown($event, count)"
        @input="scope.row.count=/^\d+\.?\d{0,2}$/.test(count)||count == '' ? count : count=checkValue">
</template>
<script>
    data() {
        return {
            count: '',
            checkValue: ''
        }
    },
    methods: {
        checkKeydown(e, value){
            this.checkValue = value;
        }
    }
</script>

这样已经可以实现需求了,在输入不匹配的时候,输入框输入不进去内容。大佬们有更好的解决方法,也可以在评论区讨论。

posted on 2021-02-20 18:06  小范范xf  阅读(1552)  评论(0)    收藏  举报

导航