** * @example * v-input-float="{ limit: 1, min: 0, max: 100 }" 只允许输入一位小数 * @param limit 小数位数 * @param min 最小值 * @param max 最大值 * * @since 2020.05.26 */ export const InputFloat: DirectiveOptions = { bind: (el, bind) => { const input = el.nodeName.toLowerCase() === 'input' ? (el as HTMLInputElement) : el.getElementsByTagName('input')[0] // 改变值过后,需要主动触发input时间,组件绑定的值才会改变 let triggerBySelf = false if (input) { input.addEventListener('input', () => { if (triggerBySelf) { triggerBySelf = false return } let val = input.value.replace(/[^0-9.]/gi, '') if (val === '') return const valArr = val.split('.') if (bind.expression) { try { const option = bind.value if (typeof option === 'object') { const { limit, min, max } = option if (limit !== undefined) { if (valArr.length > 1) { let pointLength = valArr[1].length pointLength = limit > pointLength ? pointLength : limit if (limit > 0) { val = +valArr[0] + (valArr.length > 1 ? `.${valArr[1].substr(0, pointLength)}` : '') } else { val = +valArr[0] + '' } } else { val = +val + '' } } if (typeof min === 'number' && +val < +min) { val = min + '' } if (typeof max === 'number' && +val > +max) { val = max + '' } // 改变值过后,需要主动触发input时间,组件绑定的值才会改变 const ev = new Event('input', { bubbles: true }) input.value = val triggerBySelf = true input.dispatchEvent(ev) } } catch (err) { input.value = val console.error(err) } } }) } } }