index.ts
import type { App } from 'vue'
import { setupTrimDirective } from './trim'
import { setupDraggableDirective } from './draggable'
export default function setupGlobDirectives(app: App) {
setupTrimDirective(app)
setupDraggableDirective(app)
}
import setupGlobDirectives from '@/directives'
setupGlobDirectives(app)
trim.ts
import type { App, Directive } from 'vue'
const regExpSpace = /(^\s+)|(\s+$)/g
const trimDirective: Directive = {
created(el: Element) {
function getInputTarget(el: Element): Element | undefined {
if (el.nodeName === 'INPUT') return el
return Array.from(el.children).find((item) => getInputTarget(item))
}
const input = getInputTarget(el)
if (!input) return
const updateInputValue = (e: Event) => {
;(e.target as HTMLInputElement).value = (
e.target as HTMLInputElement
).value.replace(regExpSpace, '')
input.dispatchEvent(new Event('input'))
}
input.addEventListener(
'keydown',
(e: any) => {
if ((e as KeyboardEvent).keyCode !== 13) return
updateInputValue(e)
},
true
)
input.addEventListener('blur', updateInputValue, true)
}
}
export function setupTrimDirective(app: App) {
app.directive('trim', trimDirective)
}
export default trimDirective