效果图
初衷
金融项目 金额较大单位需要精确到元
网上很多方案大多数都是为输入框注册blur事件然后进行千分位处理再对应赋值
感觉比较麻烦 刚好最近比较喜欢写指令 所以写了个通用指令
代码
// 千分位
Vue.directive('thousands', {
bind(el, binding, vnode: any) {
const key = Object.keys(binding.modifiers)[0]
// 处理千分位展示
const generatingThousandthPer = (num: any) => {
let num1 = num.split(".")[0], num2 = num.split(".")[1];
let c = num1.toString().replace(/(\d)(?=(?:\d{3})+$)/g, '$1,');
return num.toString().indexOf(".") !== -1 ? c + "." + num2 : c;
}
// 赋值
const assignment = (event: any, value: string, value2?: string) => {
binding.value[key] = value;
vnode.context.$nextTick(() => event.target.value = generatingThousandthPer(value2 || value))
}
// 处理最后一位非法字符
const handlerIllegalStr = (str: string) => {
while (!(/^[0-9]+.?[0-9]*/.test(str.charAt(str.length - 1)))) {
str = str.substr(0, str.length - 1)
}
return str
}
el.addEventListener("input", (event: any) => {
let inp = event.target.value = event.target.value.replace(/,/g, "")
assignment(event, inp)
})
// element
const input = $(el).find(".el-input__inner")
if (input) {
input[0].addEventListener("blur", (event: any) => {
const val = event.target.value;
if (!val || !/^[0-9]+.?[0-9]*/.test(val)) return;
assignment(event, handlerIllegalStr(val.replace(/,/g, "")))
})
}
}
});
用法
<el-input
v-thousands.registeredCapital="ruleForm1.workInfo"
v-model.trim="ruleForm1.workInfo.registeredCapital"
></el-input>