vue3过滤输入框首尾空格
在 directive文件夹下 新建 trim.ts 文件
import { App } from "vue"
function getInput ( el: { tagName: string ; querySelector : ( arg0: string ) => any } ) {
let inputEle
if ( el. tagName !== 'INPUT' ) {
inputEle = el. querySelector ( 'input' ) || el. querySelector ( 'textarea' )
} else {
inputEle = el
}
return inputEle
}
function dispatchEvent ( el: { dispatchEvent : ( arg0: Event) => void } , type: string ) {
const evt = document. createEvent ( 'HTMLEvents' )
evt. initEvent ( type, true , true )
el. dispatchEvent ( evt)
}
export const trim = ( app: App< any > ) => {
app. directive ( 'trim' , {
mounted ( el: { inputEle: any ; _blurHandler : ( event: any ) => void ; _keyHandler : ( event: any ) => void } ) {
const inputEle = getInput ( el)
const handler = function ( event: { target: { value: string } } ) {
const newVal = event. target. value. trim ( )
if ( event. target. value !== newVal) {
event. target. value = newVal
dispatchEvent ( inputEle, 'input' )
}
}
const keydown = function ( event: { keyCode: number ; target: { value: string } } ) {
if ( event. keyCode === 13 ) {
const newVal = event. target. value. trim ( )
if ( event. target. value !== newVal) {
event. target. value = newVal
dispatchEvent ( inputEle, 'input' )
}
}
}
el. inputEle = inputEle
el. _blurHandler = handler
el. _keyHandler = keydown
inputEle. addEventListener ( 'blur' , handler)
inputEle. addEventListener ( 'keydown' , keydown)
} ,
unmounted ( el: { _blurHandler? : any ; _keyHandler? : any ; inputEle? : any } ) {
const { inputEle } = el
inputEle. removeEventListener ( 'blur' , el. _blurHandler)
inputEle. removeEventListener ( 'keydown' , el. _keyHandler)
}
} )
}
在 directive文件夹下 新建 index.ts 文件
import type { App } from 'vue' ;
import { trim} from '/@/directive/trim'
export function directive ( app: App) {
trim ( app) ;
}
在 main.ts中引入
import { directive } from '/@/directive/index' ;
const app = createApp ( App) ;
directive ( app) ;
app. mount ( '#app' )
使用
< el- form- item : label= "$t('message.application.table.description')" prop= "applicationDescribe" >
< el- input v- trim maxlength= "200" show- word- limit v- model= "form.applicationDescribe" : rows= "2"
type= "textarea" : placeholder= "$t('message.application.table.Pleasedescription')" / >
< / el- form- item>