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>
相关推荐
代码搬运媛4 小时前
Jest 测试框架详解与实现指南
前端
counterxing5 小时前
我把 Codex 里的 Skills 做成了一个 MCP,还支持分享
前端·agent·ai编程
wangqiaowq5 小时前
windows下nginx的安装
linux·服务器·前端
之歆6 小时前
DAY_12JavaScript DOM 完全指南(二):实战与性能篇
开发语言·前端·javascript·ecmascript
发现一只大呆瓜6 小时前
Vite凭什么这么快?3分钟带你彻底搞懂 Vite 热更新的幕后黑手
前端·面试·vite
Maimai108086 小时前
React如何用 @microsoft/fetch-event-source 落地 SSE:比原生 EventSource 更灵活的实时推送方案
前端·javascript·react.js·microsoft·前端框架·reactjs·webassembly
candyTong6 小时前
Claude Code 的 Edit 工具是怎么工作的
javascript·后端·架构
kyriewen7 小时前
产品经理把PRD写成“天书”,我用AI半小时重写了一遍,他当场愣住
前端·ai编程·cursor
humcomm8 小时前
元框架的工作原理详解
前端·前端框架
canonical_entropy8 小时前
Attractor Before Harness: AI 大规模开发的方法论
前端·aigc·ai编程