input[type=numer] 虽然规避了字母和特殊字符,但又出现 0.0000不受控制的情况,故又改为 input[type=text] 用字符串的方式控制及将特殊字符替换成空字符串''
<template>
<input v-model="extractMoney" maxlength="8" placeholder-style="" :placeholder="'请输入'" />
</template>
<script setup lang="ts">
import { ref, watch, nextTick } from 'vue';
const extractMoney = ref<string | null>();
watch(extractMoney, (_newValue, _oldValue) => {
// 小数点后两位
if (_newValue && /^\d+(?:\.\d{0,2})?/.test(_newValue)) {
nextTick(() => {
extractMoney.value = String(_newValue.replace(/e/g, '').match(/^\d+(?:\.\d{0,2})?/));
});
return;
}
// 替换字母特殊字符空格
if (_newValue && /[a-zA-Z!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\s]+/.test(_newValue)) {
nextTick(() => {
extractMoney.value = _newValue.replace(/[a-zA-Z!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\s]+/g, '');
});
return;
}
});
const onSubmit = () => {
const nowNumber = Number(Number(extractMoney.value).toFixed(2))
}
</script>
原生js可以用
οnkeyup="value = (String(value) || '').replace(/e/g, '').match(/^\d+(?:\.\d{0,2})?/)"