import Vue from 'vue'

//input 限制输入字数
//v-toInputNum= {num:4}

Vue.directive('toInputNum', {
    // 指令的定义
    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) {
                checkValue(dom, binding.value.num)
            } else {
                checkValue(dom, 50)
            }
        })
        function checkValue(el, defu) {
            let len = el.value.length
            if (el.value && len > defu) {
                el.value = el.value.substring(0, defu-1);
                el.dispatchEvent(new Event("input"));//调用input事件使vue v-model绑定更新
            }
        }
    }
})
