• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

使用自定义指令,对el-input做正则校验

武飞扬头像
six_
帮助1

@/directives/index.ts

fix: 中文输入法导致 dispatch input 的问题

import Vue, { DirectiveBinding } from 'vue'

// 去除el-input框的空格
const trigger = (el: HTMLElement) => {
  const e = new InputEvent('input')
  el.dispatchEvent(e)
}
// 例: v-trimReg="/[\u4E00-\u9FA5]/":不能输入汉字;
// v-trimReg="/[^a-zA-Z0-9]/g":只能输入英文和数字
// v-trimReg="/[^0-9]/g":只能输入数字
const EventRecordMap = new Map<HTMLInputElement, EventListenerOrEventListenerObject[]>()
Vue.directive('trimReg', {
  bind: function (el: HTMLElement, binding: DirectiveBinding<RegExp>) {
    const reg = binding.value
    const input = (el.querySelector('input') || el.querySelector('textarea')) as HTMLInputElement
    if(!input) return
    let isComposing = false
    const event: EventListenerOrEventListenerObject = (ev) => {
      if(isComposing) return
      const e = ev as InputEvent
      const dom = e.target as HTMLInputElement
      if(reg.test(dom.value ?? '')) {
        dom.value = dom.value.replace(reg, '')
        trigger(dom)
      }
    }
    // 开始中文输入法
    function compositionstart() {
      isComposing = true
    }
    // 结束中文输入法
    function compositionend(e: Event) {
      isComposing = false
      const dom = e.target as HTMLInputElement
      trigger(dom)
    }

    EventRecordMap.set(input, [event, compositionstart, compositionend])
    input.addEventListener('compositionstart', compositionstart)
    input.addEventListener('compositionend', compositionend)
    input.addEventListener('input', event)
  },
  unbind: function(el: HTMLElement) {
    const input = (el.querySelector('input') || el.querySelector('textarea')) as HTMLInputElement
    if(!input) return
    if(EventRecordMap.has(input)) {
      const events = EventRecordMap.get(input)!
      input.removeEventListener('input', events[0])
      input.removeEventListener('compositionstart', events[1])
      input.removeEventListener('compositionend', events[2])
      EventRecordMap.delete(input)
    }
  }
})

src/main.ts

import Vue from 'vue'

import 'normalize.css'
import ElementUI from 'element-ui'
import zhLocale from 'element-ui/lib/locale/lang/zh-CN'
import { createPinia, PiniaVuePlugin } from 'pinia'

import '@/styles/element-variables.scss'
import '@/styles/index.scss'

import App from '@/App.vue'
import router, { constantRoutes, dynamicRoutes } from '@/router/index'
import '@/icons'
import permission from '@/permission/index'
import type { PermissionPluginConfig } from '@/permission'

import globalComponent from '@/components/globalComponent'
import filters from '@/filters'

import { AuthCode, AuthEnabled } from '@/config'
import { isLogin } from '@/utils/auth'
import { redirectToLogin } from '@/utils'

import '@/utils/number'
import { useUserStore } from './store/user'
// 引入自定义指令
import '@/directives/index'

Vue.use(ElementUI, {
  size: 'small',
  locale: {
    el: {
      // 修改分页组件默认配置
      ...zhLocale.el,
      pagination: {
        pagesize: '条/页',
        total: `共 {total} 条`,
        goto: '跳至',
        pageClassifier: '页'
      }
    }
  }
})

Vue.use(filters)

const pinia = createPinia()
Vue.use(PiniaVuePlugin)
const userStore = useUserStore(pinia)

const permissionPluginConfig: PermissionPluginConfig = {
  enabled: {
    menu: AuthEnabled.Menu,
    btn: AuthEnabled.Btn
  },
  authCode: AuthCode,
  router,
  constantRoutes,
  dynamicRoutes,
  fetchAuthRoutes: () =>
    userStore.getUserAuthorizedData().then((res) => res.asyncRoutes),
  loginMethods: {
    checkIsLogin: isLogin,
    redirectToLogin,
    logout: () => userStore.logOut(),
    checkIsRoutesLoaded: () => userStore.isMenuGet
  }
}
Vue.use(permission, permissionPluginConfig)

Vue.use(globalComponent)
Vue.config.productionTip = false


new Vue({
  router,
  pinia,
  render: (h) => h(App)
}).$mount('#app')

使用

<el-input
  v-model="teacher.userName"
  placeholder="请填写系统用户名"
  clearable
  :maxlength="15"
  v-trimReg="/[^0-9a-zA-Z]/g"
></el-input>

<el-input
  v-model.trim="teacher.workYear"
  placeholder="请填写从业年限"
  clearable
  v-trimReg="/[^0-9]/g"
></el-input>

//数字和字母
/[^0-9a-zA-Z]/g

//纯数字
/[^0-9]/g

//只能输入中文、数字以及“-”
/[^\u4e00-\u9fa5\\^0-9a-zA-Z\\-]/g

只能输入字母、数字以及“-”
/[^0-9a-zA-Z\\-]/g








备用文件

@/directives/index.ts

import Vue, { DirectiveBinding } from 'vue'

// 去除el-input框的空格
const trigger = (el: HTMLElement, type: string) => {
  const e = document.createEvent('Event')
  e.initEvent(type, true, true)
  el.dispatchEvent(e)
}
// 例: v-trimReg="/[\u4E00-\u9FA5]/":不能输入汉字;
// v-trimReg="/[^a-zA-Z0-9]/g":只能输入英文和数字
// v-trimReg="/[^0-9]/g":只能输入数字
const EventRecordMap = new Map<HTMLInputElement, EventListenerOrEventListenerObject>()
Vue.directive('trimReg', {
  bind: function (el: HTMLElement, binding: DirectiveBinding<RegExp>) {
    const reg = binding.value
    const input = (el.querySelector('input') || el.querySelector('textarea')) as HTMLInputElement
    if(!input) return
    const event = () => {
      const value = input.value
      if(reg.test(value)) {
        input.value = value.replace(reg, '')
        trigger(input, 'input')
      }
    }
    EventRecordMap.set(input, event)
    input.addEventListener('input', event)
  },
  unbind: function(el: HTMLElement) {
    const input = (el.querySelector('input') || el.querySelector('textarea')) as HTMLInputElement
    if(!input) return
    if(EventRecordMap.has(input)) {
      input.removeEventListener('input', EventRecordMap.get(input)!)
      EventRecordMap.delete(input)
    }
  }
})

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhgbajag
系列文章
更多 icon
同类精品
更多 icon
继续加载