Element Plus中的el-input-number组件禁止输入小数点.

0 阅读1分钟

ElInputNumber 组件虽然有属性 precision 可是设置小数点位数,但是校验的时机时在失去焦点的时候,用户在输入的同时是可以看到小数点的,有些项目中的需求是禁止输入小数点。

改造ElInput组件 type为string 通过监听value值进行正则校验即可

<script lang="ts" setup>
import { Minus, Plus } from '@element-plus/icons-vue'

import {ref, watch, defineOptions,defineProps } from 'vue'

defineOptions({
    inheritAttrs: false
})

const props = defineProps({
    modelValue: {
        type: [Number],
        default: 1
    },
    min: {
        type: Number,
        default: 1
    },
    max: {
        type: Number,
        default: null
    },
    step: {
        type: Number,
        default: 1
    }
})

const inputValue = ref(props.min)

const emit = defineEmits(['update:modelValue', 'change']);

watch(
    () => props.modelValue,
    (newVal) => {
        inputValue.value = newVal;
    }
)

watch(inputValue, (val, preVal) => {
    let _val = val
    if (!/^[\d]*$/g.test(String(val))) {
        inputValue.value = Number(preVal)
        _val = Number(preVal)
    } else {
        inputValue.value = Number(val)
        _val = Number(val)
    }
    emit('update:modelValue', _val);
    emit('change', _val);
})

const decrease = () => {
    if (inputValue.value === props.min) return
    inputValue.value = Number(inputValue.value) - props.step
}

const increase = () => {
    if (!inputValue.value) {
        inputValue.value = 0
    }
    inputValue.value = Number(inputValue.value) + props.step
}
</script>

<template>
    <el-input v-model="inputValue" v-bind="$attrs">
        <template #prepend>
            <el-icon @click="decrease" :class="props.min === inputValue ? 'is-disabled' : ''">
                <Minus />
            </el-icon>
        </template>
        <template #append>
            <el-icon @click="increase">
                <Plus />
            </el-icon>
        </template>
    </el-input>
</template>

tips: 样式自行定义