import { Directive } from 'vue'
const getInput = (el: HTMLElement) => {
let inputEl: HTMLElement | null
if (el.tagName !== 'INPUT') {
inputEl = el.querySelector('input') || el.querySelector('textarea')
} else {
inputEl = el
}
return inputEl
}
interface Ele extends HTMLElement {
inputEl: HTMLElement | null
_blurHandler: (event: Event) => void
}
const dispatchEvent = (el: HTMLElement | null, type: string) => {
const evt = document.createEvent('HTMLEvents')
evt.initEvent(type, true, true)
el?.dispatchEvent(evt)
}
const elInputTrim: Directive = {
mounted(el: Ele) {
const inputEl = getInput(el)
const handler = function (event: Event) {
let newVal = (event.target as HTMLInputElement).value.trim()
// 文字间连续多个空格替换为一个 例如 “我 和 你” =》 “我 和 你”
newVal = newVal.replace(/\s{2,}/g, ' ')
if ((event.target as HTMLInputElement).value !== newVal) {
;(event.target as HTMLInputElement).value = newVal
dispatchEvent(inputEl, 'input')
}
}
el.inputEl = inputEl
el._blurHandler = handler
inputEl?.addEventListener('blur', handler)
},
unmounted(el: Ele) {
const { inputEl } = el
inputEl?.removeEventListener('blur', el._blurHandler)
}
}
export default elInputTrim