Advertisement
Guest User

Untitled

a guest
Aug 19th, 2019
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.05 KB | None | 0 0
  1. export default class NumericDirective {
  2. constructor (input, binding) {
  3. Object.assign(this, { input, binding });
  4. input.addEventListener('keydown', this);
  5. input.addEventListener('change', this);
  6. }
  7.  
  8. static install (Vue) {
  9. Vue.directive('decimal', this.directive);
  10. Vue.directive('integer', this.directive);
  11. }
  12.  
  13. static directive = {
  14. bind (el, binding) {
  15. el = el.querySelector('input');
  16. if (el) {
  17. return new NumericDirective(el, binding);
  18. }
  19. }
  20. }
  21.  
  22. handleEvent (event) {
  23. this[event.type](event);
  24. }
  25.  
  26. keydown (event) {
  27. const { target, key, keyCode, ctrlKey } = event;
  28. if (!(
  29. (key >= '0' && key <= '9') ||
  30. (
  31. ((key === '.' && this.binding.name === 'decimal') || (key === '-' && !this.binding.modifiers.unsigned)) &&
  32. !~target.value.indexOf(key)
  33. ) ||
  34. [
  35. 'Delete', 'Backspace', 'Tab', 'Esc', 'Escape', 'Enter',
  36. 'Home', 'End', 'PageUp', 'PageDown', 'Del', 'Delete',
  37. 'Left', 'ArrowLeft', 'Right', 'ArrowRight', 'Insert',
  38. 'Up', 'ArrowUp', 'Down', 'ArrowDown'
  39. ].includes(key) ||
  40. // ctrl+a, c, x, v
  41. (ctrlKey && [65, 67, 86, 88].includes(keyCode))
  42. )) {
  43. event.preventDefault();
  44. }
  45. }
  46.  
  47. change ({ target }) {
  48. const isDecimal = this.binding.name === 'decimal';
  49. let value = target.value;
  50. if (!value) {
  51. return;
  52. }
  53. const isNegative = /^\s*-/.test(value) && !this.binding.modifiers.unsigned;
  54. value = value.replace(isDecimal ? /[^\d,.]/g : /\D/g, '');
  55. if (isDecimal) {
  56. const pieces = value.split(/[,.]/);
  57. const decimal = pieces.pop().replace(/0+$/, '');
  58. if (pieces.length) {
  59. value = `${pieces.join('') || (decimal ? '0' : '')}${decimal ? `.${decimal}` : ''}`;
  60. }
  61. }
  62. value = value.replace(/^(?:0(?!\b))+/, '');
  63. if (value && isNegative) {
  64. value = `-${value}`;
  65. }
  66. if (target.value !== value) {
  67. target.value = value;
  68. const event = document.createEvent('UIEvent');
  69. event.initEvent('input', true, false, window, 0);
  70. target.dispatchEvent(event);
  71. }
  72. }
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement