1. 仅输入数字
// <input v-only-number>
Vue.directive('onlyNumber', {
inserted: function (targetDom) {
targetDom.addEventListener('keypress', function (event) {
event = event || window.event;
let charcode = typeof event.charCode === 'number' ? event.charCode : event.keyCode;
if (!/\d/.test(String.fromCharCode(charcode)) && charcode > 9 && !event.ctrlKey) {
if (event.preventDefault) {
event.preventDefault();
} else {
event.returnValue = false;
}
}
});
}
});
复制代码
2. 自动聚焦
// <input v-focus>
Vue.directive('focus', {
inserted: function (el) {
el.focus()
}
})
复制代码
3.点击复制到剪切板
// <div v-copy="number">copy</div>
Vue.directive('copy', {
bind: function (targetDom) {
targetDom.addEventListener('click', function (event) {
let $input = document.createElement('textarea')
$input.style.opacity = '0'
$input.value = targetDom.dataset.copyValue
document.body.appendChild($input)
$input.select()
document.execCommand('copy')
document.body.removeChild($input)
$input = null
});
},
// 更新存储的值,存储在 dom 的 dataset 中
update: function (el, binding) {
el.dataset.copyValue = binding.value
}
})
复制代码
4. 快捷键映射
// <div v-shortcut="{'27': key1}">copy</div>
Vue.directive('shortcut', {
bind: function (targetDom, binding) {
// 往 dom 对象中挂载函数,以便卸载时,消除消息监听,keyCode 编码映射表:https://www.bejson.com/othertools/keycodes/
targetDom.shortcutFun = function (event) {
Object.keys(binding.value).forEach((key) => {
event.keyCode.toString() === key && binding.value[key]()
})
}
window.addEventListener('keyup', targetDom.shortcutFun)
},
// 指令被卸载,消除消息监听
unbind: function (targetDom) {
window.removeEventListener('keyup', targetDom.shortcutFun)
}
})
复制代码
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END






















![[桜井宁宁]COS和泉纱雾超可爱写真福利集-一一网](https://www.proyy.com/skycj/data/images/2020-12-13/4d3cf227a85d7e79f5d6b4efb6bde3e8.jpg)

![[桜井宁宁] 爆乳奶牛少女cos写真-一一网](https://www.proyy.com/skycj/data/images/2020-12-13/d40483e126fcf567894e89c65eaca655.jpg)