vue自定义指令千分位

发布于:2025-02-26 ⋅ 阅读:(9) ⋅ 点赞:(0)

问题

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

解决

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

自定义指令-千分位

// 自定义指令-千分位
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只能输入,并且加上千分位指令

   <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>