如何基于vue3 封装敏感词过滤自定义指令(输入框输入时 自动将敏感词转成**)

如何基于vue3 封装敏感词过滤自定义指令

实现功能:el-input输入框输入时 自动将敏感词转成**

  • 1.在src下创建directive文件=>filterSensitiveWords.ts
import type { App } from 'vue'
const sensitiveWords = ['敏感词1', '敏感词2', '敏感词3']
export function filterSensitiveWords(app: App) {
  app.directive('filter', {
    //在绑定元素的父组件被挂载后调用
    mounted(el, binding) {
      let timeout: any
      el.addEventListener('input', function (event: any) {
        clearTimeout(timeout)
        timeout = setTimeout(async () => {
          const input = event.target.value
          if (!input) {
            return
          }
          const filteredInput = await filterFn(input)
          event.target.value = filteredInput
          el.dispatchEvent(new Event('input'))
        }, 300)
      })
    },
    //卸载
    unmounted(el) {
      console.log('自定义指令卸载', el)
      el.addEventListener('input', () => {})
    },
  })
}

//过滤方法
function filterFn(input: string): string {
  let filteredInput = input
  for (let i = 0; i < sensitiveWords.length; i++) {
    const sensitiveWord = sensitiveWords[i]
    const regex = new RegExp(sensitiveWord, 'gi')
    filteredInput = filteredInput.replace(
      regex,
      '*'.repeat(sensitiveWord.length)
    )
  }
  return filteredInput
}

  • 2.main.ts挂载指令
//引入自定义指令
import { directive } from '@/directive/index'

const app = createApp(App)
directive(app) //挂载指令
  • 3.使用自定义指令
 <el-input v-filter v-model="iptValue">el-input>

你可能感兴趣的:(vue3,vue.js,javascript,前端)