vue3自定义全局指令(过滤前后空格,输入框自动聚焦、点击复制文本到粘贴板)

背景:产品要求,客户输入框可以输入空格,但提交数据的时候需要过滤前后空格。这就导致了v-model.trim不能用,因为trim会限制用户的输入。
项目结构:

main.js (指令挂载到全局)

import { createApp } from 'vue'
import App from './App.vue'
import defineDirectives from '@/directive/index

const app = createApp(App)
defineDirectives(app)
app.mount('#app')

directive->index.js

import $ from 'jquery'

function getInput(el) {
  let inputEle
  if (el.tagName !== 'INPUT') {
    inputEle = el.querySelector('input')
  } else {
    inputEle = el
  }
  return inputEle
}
function dispatchEvent(el, type) {
  const evt = document.createEvent('HTMLEvents')
  evt.initEvent(type, true, true)
  el.dispatchEvent(evt)
}
// 聚焦指令 v-focus
const focus = (app) => {
  app.directive('focus', {
    mounted(el) {
      const children = $(el).find('input')[0]
      $(children).focus()
    }
  })
}
// 过滤前后空格的指令 v-trim
const trim = (app) => {
  app.directive('trim', {
    mounted(el) {
      const inputEle = getInput(el)
      const handler = function(event) {
        const newVal = event.target.value.trim()
        if (event.target.value !== newVal) {
          event.target.value = newVal
          dispatchEvent(inputEle, 'input')
        }
      }
      // 回车后过滤空格
      const keydown = function(event) {
        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) {
      const { inputEle } = el
      inputEle.removeEventListener('blur', el._blurHandler)
      inputEle.removeEventListener('keydown', el._keyHandler)
    }
  })
}
export default (app) => {
  focus(app)
  trim(app)
}

在页面中的用法(因为是全局引入,单页面直接用即可)

// v-trim 可实现正常输入,但离开焦点或者回车,会过滤前后空格
// v-focus 实现打开页面自动聚焦
<el-input v-model="name" v-trim v-focus placeholder="请输入" @keyup.enter="getList" />

单击复制功能参考本人博客:单击复制

posted @ 2022-06-15 13:59  OYLY  阅读(893)  评论(1编辑  收藏  举报