import Vue from 'vue'

//input 限制输入正整数
//v-toInt={maxNum: 最大值，notNum：不等于}
Vue.directive('toInt', {
    // 指令的定义
    inserted: function(el, binding, vnode) {
        let dom = null
        if (el.tagName == 'INPUT') {
            dom = el
        } else {
            dom = el.querySelector('input')
        }
        dom.addEventListener("input", function() {
            //进行验证
            if (binding.value) {
                checkedfun(dom, binding.value.maxNum, binding.value.notNum)
            } else {
                checkedfun(dom, null, null)
            }
        });
        function checkedfun(el, maxNum, notNum) {
            if (maxNum && el.value > maxNum) {
                el.value = maxNum
                el.dispatchEvent(new Event("input"));//调用input事件使vue v-model绑定更新
            }
            if (notNum && typeof (notNum) !=='undefined' && el.value === notNum.toString()) {
                el.value = ''
                el.dispatchEvent(new Event("input"));//调用input事件使vue v-model绑定更新
            }

        let reg = new RegExp("^[0-9]*$");
            if (!reg.test(el.value)) {
                el.value = el.value.replace(/[^0-9]+/g, "");
                el.dispatchEvent(new Event("input"));//调用input事件使vue v-model绑定更新
            }
        }
    }
})
