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>
相关推荐
JarvanMo3 分钟前
Flutter 中的微服务架构:拆解你的应用
前端
JarvanMo4 分钟前
对我来说,那个框架就是 Flutter。
前端
Mintopia12 分钟前
🧠 自监督学习在 WebAIGC 中的技术突破与应用前景
前端·人工智能·aigc
Mintopia14 分钟前
🧭 传统 Web 开发最好的 AI 助手框架排行榜(2025版)
前端·人工智能·aigc
坚持就完事了25 分钟前
003-HTML之表单
服务器·前端·html
暖木生晖26 分钟前
Javascript函数之匿名函数以及立即执行函数的使用方法?
开发语言·javascript·ecmascript
一 乐33 分钟前
医疗管理|医院医疗管理系统|基于springboot+vue医疗管理系统设计与实现(源码+数据库+文档)
java·数据库·vue.js·spring boot·后端·医疗管理系统
光影少年36 分钟前
React Native第六章
javascript·react native·react.js
晓得迷路了39 分钟前
栗子前端技术周刊第 105 期 - npm 安全性加强、Storybook 10、htmx 4.0 Alpha 1...
前端·javascript·npm