input 只能输入正整数 和小数点,小数点限制一位。
<input oninput="value=value.replace(/[^\d.]/g,'')
.replace(/\.{2,}/g,'.')
.replace(/^\./g,'')"
/>
- .replace(/[^\d.]/g,‘’) 非数字型的转换为空
- .replace(/.{2,}/g,‘.’) 连续小数点替换成一个 如:
1...2 => 1.2 - .replace(/^./g,‘’) 以
. 开头的替换'' 如:.42 => 42 - .replace(/(…*)./g, ‘$1’) 只保留第一个小数点删除后面的
- .replace(/(…*)./g, ‘’) 小数点转换为空 如:
12. => 12
main.ts
import { installDirective } from "./utils/directive";
const app = createApp(App);
installDirective(app);
directive.ts
import type { App } from "vue";
export const installDirective = (app: App) => {
app.directive("number-input", {
mounted(el) {
el.addEventListener("input", e => {
let val = e.target.value
.replace(/[^\d.]/g, "")
.replace(/\.{2,}/g, ".")
.replace(/^\./, "")
.replace(/(\..*)\./g, "$1");
if (val !== e.target.value) {
e.target.value = val;
e.target.dispatchEvent(new Event("input"));
}
});
},
});
};
使用 <input v-number-input />