1. Enter only numbers
// <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; }}}); }});Copy the code
2. Auto focus
// <input v-focus>
Vue.directive('focus', {
inserted: function (el) {
el.focus()
}
})
Copy the code
3. Click Copy to clipboard
// <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 }); Update: function (el, binding) {el.dataset. CopyValue = binding. Value}})Copy the code
4. Shortcut key mapping
// <div v-shortcut="{'27': key1}">copy</div> Vue.directive('shortcut', { bind: Function (targetDom, binding) {// Mount the function to the DOM object, so that when unmount, eliminate the message listener, keyCode code mapping table: 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)}, function (targetDom) { window.removeEventListener('keyup', targetDom.shortcutFun) } })Copy the code