乐趣区

关于vue.js:vue2-element-ui-input输入格式限制

import Vue from "vue";

/**
 * element-input 输出限度
 *
 */
//v-positiveInteger  正整数
//v-positiveInteger.2  保留两位小数
//v-positiveInteger.4  保留四位小数
Vue.directive("positiveInteger", {bind(el, binding, vnode) {let dom = findDom(el, "el-input__inner");
        let modifiers = binding.modifiers
        let mantissa = 0
        for (let x in modifiers) {mantissa = x}
        el.handler = function () {if (vnode.inputLocking) {return;}
            if(mantissa) {let reg = new RegExp(`^\\D*(\\d*(?:\.\\d{0,${mantissa}})?).*$`, 'gmi')
                el.childNodes[1].value = el.childNodes[1].value.replace(reg, "$1");
            }else {el.childNodes[1].value = el.childNodes[1].value.replace(/\D+/g, "");
            }
            
        };
        dom.addEventListener("compositionstart", () => {vnode.inputLocking = true;});
        dom.addEventListener("compositionend", () => {
            vnode.inputLocking = false;
            dom.dispatchEvent(new Event("input"));
        });
        dom.onfocus = function () {if (dom.value == 0) {dom.value = "";}
        };
        el.addEventListener("keyup", el.handler);
        el.handler1 = function () {el.childNodes[1].value = el.childNodes[1].value;
            dom.dispatchEvent(new Event("input"));
        };
        el.childNodes[1].addEventListener("blur", el.handler1);
    },
    unbind(el) {el.removeEventListener("keyup", el.handler);
        el.childNodes[1].removeEventListener("blur", el.handler);
    },
});
// 递归查找某个元素节点
function findDom(el, className) {
    let dom;
    for (let i = 0; i < el.childNodes.length; i++) {if (el.childNodes[i].nodeType == 1) {let str = el.childNodes[i].getAttribute("class");
            if (str.indexOf(className) > -1) {dom = el.childNodes[i];
                break;
            } else {dom = findDom(el.childNodes[i], className);
            }
        }
    }
    return dom;
}

参考文章

退出移动版