Vue限制输入框内容只能输入金额或数字

Vue限制输入框内容只能输入金额或数字

HaoOuBa
2021-02-20 / 5 评论 / 582 阅读 / 正在检测是否收录...
温馨提示:
本文最后更新于2021年02月20日,已超过1252天没有更新,若内容或图片失效,请留言反馈。
<template>
    <input @input="formatValue(value)" v-model="value">
</template>

<script>
    export default = {
        data(){
            return {
                value: ""
            }
        },
        methods:{
            // 只允许输入数字,其他一律不允许输入
            formatValue(val){
                this.value = this.value.replace(/[^\d]/g, "")
            },

            // 只允许输入金额类型,最大两位小数(如:3.88)
            formatValue(val){
                val = val.replace(/(^\s*)|(\s*$)/g, "");
                if (!val) return this.value = "";
                val = val.replace(/[^\d.]/g, "");
                val = val.replace(/^\./g, "");
                val = val
                    .replace(".", "$#$")
                    .replace(/\./g, "")
                    .replace("$#$", ".");
                val = val.replace(/^(\-)*(\d+)\.(\d\d).*$/, "$1$2.$3");
                this.value = val;
            },
        }
    }
</script>
2

评论 (5)

取消
  1. 头像
    d
    Windows 10 · Google Chrome

    㸔 ِ黃 ِ魸3xne.xyz 偸 ِ啪

    回复
  2. 头像
    你好
    MacOS · Google Chrome

    画图

    回复
  3. 头像
    黑丝永远的神
    Windows 10 · Google Chrome

    画图

    回复
  4. 头像
    小刀
    Windows 10 · Google Chrome

    画图

    回复
  5. 头像
    看了吗
    Android · Google Chrome

    画图

    回复