describe

Description of the project often encountered some in the text input box can only enter a number or the specified number of decimal requirements, if you can do a unified instruction, this part of the requirements of packaging reuse, use will be a lot more convenient.

Here’s the float.js directive that limits the decimals input:

// Input box limit decimal input rules, can limit the specified decimal point before the input length, specified after the decimal point number

   const specialInputFloatContext = '@@specialInputFloatContext';

   export default {

     bindfunction (el,binding,vNode{

       let {totalDigit=1,pointAfterDigit=1}=binding.value;

       let dealInputVal=(value,pointAfterDigit=0) = > {

           value = value.replace(/ * ^ 0 (0 \. | [1-9]) /."$1");

           value = value.replace(/[^\d.]/g.""); // Clear characters other than "numbers" and "."

           value = value.replace(/^\./g.""); // Verify that the first character is a number and not a character

           value = value.replace(/\.{1,}/g."."); // Keep only the first one. Clear of excess

           value = value

           .replace("."."$# $")

           .replace(/\./g."")

           .replace("$# $".".");


           let str=' ';

           for(let i=0; i<pointAfterDigit; i++){ str+='\\d';

           }

           let reg=new RegExp('^(-)*(\\d*)\\.('+str+'). * $');

           value = value.replace(reg, "At $1, $2. $3");  //// value = value.replace(/^(-)*(\d*)\.(\d\d\d).*$/, "$1$2.$3");

           value =

           value.indexOf(".") > 0 ? value.split(".") [0].substring(0, totalDigit) + "." + value.split(".") [1] : value.substring(0, totalDigit);

           return value;

       }

       const documentHandler = function(e{
       
       // const input = el.getelementsBytagName ('input')[0] // elder-ui el-input component

         const input = el;/ / input tags

         let value=dealInputVal(input.value,pointAfterDigit);

         input.value=value

         vNode.data.model.callback(value)

       };

       el[specialInputFloatContext] = {

         documentHandler,

         arg'keyup'};document.addEventListener(el[specialInputFloatContext].arg, documentHandler);
     },

     unbind(el) {

       document.removeEventListener(

         el[specialInputFloatContext].arg,

         el[specialInputFloatContext].documentHandler);

     },

     install(Vue) {

       Vue.directive('float', {

         bindthis.bind,

         unbindthis.unbind }); }}Copy the code

Use: limit first 5 decimal places, second 2 decimal places:

<input type="text" v-model.number.trim="float" v-float='{totalDigit:5,pointAfterDigit:2}' autoComplete="off"   />
Copy the code