vue-全局自定义指令【去除空格】(左侧 右侧 两侧)

58 阅读1分钟
  1. 代码如下:
// directives/trim.js
export const trim = {
  mounted(el, binding) {
    const trimType = binding.arg || 'both' // 可以是 'left', 'right', 'both' 
    const trim = (value) => {
      switch(trimType) {
        case 'left':
          return value.trimStart()
        case 'right':
          return value.trimEnd()
        default:
          return value.trim()
      }
    }

    if (el.tagName === 'INPUT' || el.tagName === 'TEXTAREA') {
      el.addEventListener('blur', () => {
        el.value = trim(el.value)
        el.dispatchEvent(new Event('input'))
      })
    }
  },
  updated(el, binding) {
    const trimType = binding.arg || 'both'
    const trim = (value) => {
      switch(trimType) {
        case 'left':
          return value.trimStart()
        case 'right':
          return value.trimEnd()
        default:
          return value.trim()
      }
    }

    if (el.tagName === 'INPUT' || el.tagName === 'TEXTAREA') {
      el.value = trim(el.value)
      el.dispatchEvent(new Event('input'))
    }
  }
}
// directives/index.js
import { trim } from './trim'
export default {
  install(app) {
    app.directive('trim', trim)
    // 这里可以注册更多的全局指令
  }
}
  1. main.js中注册
import directive from './directive'
app.directive('trim', trim)
  1. 页面中使用
<template>
  <input v-model="value1" v-trim /> <!-- 去除两端空格 -->
  <input v-model="value2" v-trim:left /> <!-- 只去除左边空格 -->
  <input v-model="value3" v-trim:right /> <!-- 只去除右边空格 -->
</template>