vue3过滤输入框首尾空格

vue3过滤输入框首尾空格

  1. 在 directive文件夹下 新建 trim.ts 文件
    在这里插入图片描述
// 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)
}

// 过滤前后空格的指令 v-trim
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)
    }
  })
}

  1. 在 directive文件夹下 新建 index.ts 文件
// index.ts文件

import type {
    
     App } from 'vue';
import {
    
    trim} from '/@/directive/trim'
/**
 * 导出指令方法:v-xxx
 * @methods trim去除空格指令,用法:v-trim
 */
export function directive(app: App) {
    
    
    // 去除空格
	trim(app);
}
  1. 在 main.ts中引入
    在这里插入图片描述
import {
    
     directive } from '/@/directive/index';
const app = createApp(App);
directive(app);
app.mount('#app')
  1. 使用
    在这里插入图片描述
 <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>

猜你喜欢

转载自blog.csdn.net/weixin_45563734/article/details/132106081
今日推荐