问题:vue项目中如果想让一个input只能输入正整数,那么需要写一个键盘监听事件对这个input处理,但是如果有很多input需要这样处理,又或者想封装一下,怎样实现比较方便又实用?
解决办法:方便以后的使用,就需要封装一个自定义指定来的方便,就像v-if类似,实用自定就可以实现
步骤:1
1、创建
代码:注册v-Int 自定义指令
import Vue from 'vue'
export default () => {
('Int', {
inserted: function (el) {
('keypress', function (e) {
e = e ||
let charcode = typeof === 'number' ? :
let re = /\d/
if ( === 0 && charcode === 48) {
if () {
()
} else {
= false
}
} else {
if (!((charcode)) && charcode > 9 && !) {
if () {
()
} else {
= false
}
}
}
})
}
})
}
2、引入
import drectives from '@/utils/drectives'
(drectives)
3、使用 v-Int
<input type="tel" v-model="money" placeholder="请输入提现金额" @input="inputHandler" v-Int>
4、会出现中文输入的问题,下面是解决办法及其全部代码
import Vue from 'vue'
export default () => {
('Int', {
inserted: function (input) {
('keypress', function (e) {
let charcode = typeof === 'number' ? :
let re = /\d/
if ( === 0 && charcode === 48) {
if () {
()
} else {
= false
}
} else {
if (!((charcode)) && charcode > 9 && !) {
if () {
()
} else {
= false
}
}
}
})
= function (e) {
if ( === 1) {
= (/[^1-9]/g, '')
} else {
= (/[^\d]/g, '')
}
trigger(input, 'input')
}
}
})
}
const trigger = (el, type) => {
const e = ('HTMLEvents')
(type, true, true)
(e)
}
οnkeyup="value=(/[^\d]/g,'')"