vue利用自定义指令全局去除el-input框前后空格

需求

当用户输入的时候,我们需要自动去掉输入框两边的空格, 注意,中间是能输入空格的
我们一般使用的是 v-model.trim,
原生的input框是可以的,但封装之后的会把所有空格都去掉,例如el-input.

此时我们利用全局自定义指令实现对el-input的只去除首尾空格的需求。

1、在directive文件夹下创建一个trim文件夹 

  

2、index.js文件 

/**
 * 去除两边空格
 * 使用 <el-input v-model="xxx" v-trim></el-input>
 */
function getInput(el) {
      let inputEle
      if (el.tagName !== 'INPUT') {
            inputEle = el.querySelector('input')
      } else {
            inputEle = el
      }
      return inputEle
}
function dispatchEvent(el, type) {
      let evt = document.createEvent('HTMLEvents')
      evt.initEvent(type, true, true)
      el.dispatchEvent(evt)
}
const Trim = {
      inserted: el => {
            let 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')
                  }
            }
            el.inputEle = inputEle
            el._blurHandler = handler
            inputEle.addEventListener('blur', handler)
      },
      unbind(el) {
            const { inputEle } = el
            inputEle.removeEventListener('blur', el._blurHandler)
      }
}
export default Trim

3、引入

4、在main.js中全局引入定义好的directive 

import directive from './directive' // directive
Vue.use(directive)

5、使用

猜你喜欢

转载自blog.csdn.net/qq_41579104/article/details/129487774