index.ts

  1. import type { App } from 'vue'
  2. import { setupTrimDirective } from './trim'
  3. import { setupDraggableDirective } from './draggable'
  4. export default function setupGlobDirectives(app: App) {
  5. setupTrimDirective(app)
  6. setupDraggableDirective(app)
  7. }
  1. import setupGlobDirectives from '@/directives'
  2. setupGlobDirectives(app)

trim.ts

  1. import type { App, Directive } from 'vue'
  2. const regExpSpace = /(^\s+)|(\s+$)/g
  3. const trimDirective: Directive = {
  4. created(el: Element) {
  5. function getInputTarget(el: Element): Element | undefined {
  6. if (el.nodeName === 'INPUT') return el
  7. return Array.from(el.children).find((item) => getInputTarget(item))
  8. }
  9. const input = getInputTarget(el)
  10. if (!input) return
  11. const updateInputValue = (e: Event) => {
  12. ;(e.target as HTMLInputElement).value = (
  13. e.target as HTMLInputElement
  14. ).value.replace(regExpSpace, '')
  15. input.dispatchEvent(new Event('input'))
  16. }
  17. input.addEventListener(
  18. 'keydown',
  19. (e: any) => {
  20. if ((e as KeyboardEvent).keyCode !== 13) return
  21. updateInputValue(e)
  22. },
  23. true
  24. )
  25. input.addEventListener('blur', updateInputValue, true)
  26. }
  27. }
  28. export function setupTrimDirective(app: App) {
  29. app.directive('trim', trimDirective)
  30. }
  31. export default trimDirective