js
复制代码
/**
* 使用 v-only-number.positive.full="3"
*
* ="3" 表示允许输入小数,小数位数最多3位,默认为0
* positive 表示只能输入正数
* full 表示自动补零。前提是允许输入小数,否则不要写full修饰符
*
*/
Vue.directive('only-number', {
bind: function (el, {
value = 0,
modifiers
}) {
el = el.nodeName == "INPUT" ? el : el.children[0]
const RegStr = value == 0 ? `^[\\+\\-]?\\d+\\d{0,0}` : `^[\\+\\-]?\\d+\\.?\\d{0,${value}}`;
el.addEventListener('keyup', function () {
if (el.value != '-') {
el.value = el.value.match(new RegExp(RegStr, 'g'));
if (modifiers.positive) {
el.value = el.value.replace('-', '')
}
el.dispatchEvent(new Event('input'))
}
})
el.addEventListener('blur', function () {
let num = el.value.match(new RegExp(RegStr, 'g')) || '0.00';
// 自动补零
if (modifiers.fill) {
let str = num.toString()
let decimalPosition = str.indexOf('.')
if (decimalPosition < 0) {
decimalPosition = str.length
str += '.'
}
while (str.length <= (decimalPosition + Number(value))) {
str += '0'
}
num = str
el.value = num
}
if (modifiers.positive) {
el.value = el.value.replace('-', '')
}
el.dispatchEvent(new Event('input'))
})
}
})