我是 Vue.js 新手。我想要一个仅接受数字的输入字段,如果用户输入任何其他值,它将被替换为空字符串。因此,我想向该字段添加一个自定义指令,即“numericOnly”。
自定义指令代码:
Vue.directive('numericOnly', {
bind (el, binding, vnode) {
regex = /^[0-9]*$/
if(!regex.test(el.value)){
el.value = el.value.slice(0, -1)
}
}
})
这是我的模板:
<input v-numericOnly name="mobileNumber" placeholder="Mobile Number" >
但是它只在输入字段绑定到 DOM 时运行一次。
请帮我解决这个问题。预先感谢您。
您的指令应该监听输入元素的
keyup
来实现您所需要的:
Vue.directive('numericOnly', {
bind(el) {
el.addEventListener('keyup', () => {
let regex = /^[0-9]*$/
if (!regex.test(el.value)) {
el.value = el.value.slice(0, -1)
}
})
}
})
import Vue from 'vue'
Vue.directive('numericOnly', {
bind(el, binding, vnode) {
el.addEventListener('keydown', (e) => {
if ([46, 8, 9, 27, 13, 110, 190].indexOf(e.keyCode) !== -1 ||
// Allow: Ctrl+A
(e.keyCode === 65 && e.ctrlKey === true) ||
// Allow: Ctrl+C
(e.keyCode === 67 && e.ctrlKey === true) ||
// Allow: Ctrl+X
(e.keyCode === 88 && e.ctrlKey === true) ||
// Allow: home, end, left, right
(e.keyCode >= 35 && e.keyCode <= 39)) {
// let it happen, don't do anything
return
}
// Ensure that it is a number and stop the keypress
if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
e.preventDefault()
}
})
}
})
event.keyCode
属性已已弃用
我们应该使用
event.key
或 event.code
// directives/numeric-only.js
export default {
bind(el) {
el.addEventListener('keydown', function (event) {
// Allow control keys such as backspace, delete, arrows, etc.
if (
event.key === 'Backspace' ||
event.key === 'Delete' ||
event.key === 'ArrowLeft' ||
event.key === 'ArrowRight' ||
event.key === 'Tab' ||
event.key === 'Enter' ||
(event.ctrlKey && event.key === 'a') || // Allow Ctrl+A (Select All)
(event.ctrlKey && event.key === 'c') || // Allow Ctrl+C (Copy)
(event.ctrlKey && event.key === 'v') || // Allow Ctrl+V (Paste)
(event.ctrlKey && event.key === 'x') // Allow Ctrl+X (Cut)
) {
return; // Do not prevent default for these keys
}
// Allow numeric characters only
if (!/^[0-9]$/.test(event.key)) {
event.preventDefault(); // Prevent input if not a numeric character
}
});
}
};