vue自定义指令千分位

问题

开发的时候经常会遇到需要在输入框中输入数字转为千分位,点击填写时又转为数字的情况

解决

因此直接在vue中注入自定义指令,通过使用自定义指令达到效果;限制input输入框只能输入数字和一位小鼠带你

自定义指令-千分位

javascript 复制代码
// 自定义指令-千分位
Vue.directive("thousand", {
    inserted(el, binding, vnode) {
        // console.log("el", el, binding, vnode);
        // 获取input节点
        if (el.tagName.toLocaleUpperCase() !== "INPUT") {
            el = el.getElementsByTagName("input")[0];
        }
        if (!el || !el.value) return;
        // 初始化时,格式化值为千分位
        const numberValue = parseFloat(el.value.replace(/,/g, ""));
        if (!isNaN(numberValue)) {
            el.value = numberValue.toLocaleString("zh", {
                minimumFractionDigits: 2,
                maximumFractionDigits: 2,
            });
        }
        // 聚焦时转化为数字格式(去除千分位)
        el.onfocus = () => {
            el.value = parseFloat(el.value.replace(/,/g, "")).toFixed(2);
        };

        // 失去焦点时转化为千分位
        el.onblur = () => {
            console.log('aaa',el.value)
            const onBlurValue = parseFloat(el.value.replace(/,/g, ""));
            if (!isNaN(onBlurValue)) {
                el.value = onBlurValue.toLocaleString("zh", {
                    minimumFractionDigits: 2,
                    maximumFractionDigits: 2,
                });
            }
        };
    },
});

限制el-input只能输入,并且加上千分位指令

javascript 复制代码
   <el-input
   	   v-thousand
       v-model="daily_limit"
       maxlength="10"
       type="text"
       @keypress="restrictInput"
       @blur="formatOnBlur"
      >
  </el-input>

<script>
export default {
	data(){
		retrun {
 			daily_limit:''
		}
	},
methods:{
 restrictInput(event) {
     const key = event.key;
     const value = String(this.daily_limit || "");

     if (event.ctrlKey || event.altKey || key.length > 1) return;

     // 只允许数字和小数点,限制多个小数点
     const isValidKey = /[0-9.]/.test(key);
     const hasDecimal = value.includes(".");

     if (!isValidKey || (key === "." && hasDecimal)) {
          event.preventDefault();
          return;
      }
   },
 formatOnBlur(formKey) {
  	const strValue = String(this.formVal[formKey] || "");
  	if (strValue && !isNaN(Number(strValue))) {
     this.formVal[formKey] = Number(strValue).toFixed(2);
 	}
  },
 }
}
</script>
相关推荐
恋猫de小郭10 小时前
Flutter Zero 是什么?它的出现有什么意义?为什么你需要了解下?
android·前端·flutter
崔庆才丨静觅16 小时前
hCaptcha 验证码图像识别 API 对接教程
前端
passerby606117 小时前
完成前端时间处理的另一块版图
前端·github·web components
掘了17 小时前
「2025 年终总结」在所有失去的人中,我最怀念我自己
前端·后端·年终总结
崔庆才丨静觅17 小时前
实用免费的 Short URL 短链接 API 对接说明
前端
崔庆才丨静觅18 小时前
5分钟快速搭建 AI 平台并用它赚钱!
前端
崔庆才丨静觅18 小时前
比官方便宜一半以上!Midjourney API 申请及使用
前端
Moment18 小时前
富文本编辑器在 AI 时代为什么这么受欢迎
前端·javascript·后端
崔庆才丨静觅18 小时前
刷屏全网的“nano-banana”API接入指南!0.1元/张量产高清创意图,开发者必藏
前端
剪刀石头布啊18 小时前
jwt介绍
前端