测试说给项目里所有按钮加上防抖,我....

256 阅读1分钟

1. 方案

  • 新增一个自定义防抖指令 v-debounce
  • 重写项目中组件库中按钮功能,给其添加 防抖功能
  • 全局引入重写的组件

2. v-debounce 指令

  • 自定义指令
// @/directives/debounce.ts
import { debounce } from 'lodash-es'

const vDebounce = {
  created(el: any, binding: any) {
    const time = binding.value || 500
    
    let trigger = true
    const clickFunc: Function = debounce(() => {
      trigger = true
    }, time, {
      leading: true,
      trailing: false,
      ...binding.value,
    })

    el._arg = (event: Event) => {
      trigger = false
      clickFunc()
      if (!trigger) {
        event?.stopImmediatePropagation()
      }
    }

    el.addEventListener('click', el._arg, true)
  },
  unmounted(el: any) {
    el.removeEventListener('click', el._arg)
    delete el._arg
  }
}

export default vDebounce
  • 注册自定义指令
// main.ts
...
import { vDebounce } from '@/directives'
...

app.directive('debounce', vDebounce)

2. 扩展组件库按钮能力,添加防抖事件

import { ElButton } from 'element-plus'
import { defineComponent } from 'vue'

const Button = defineComponent({
  name: 'ElButton',
  setup(props, { slots }) {
    return () => (
      <ElButton {...props} v-debounce v-blur>
        {slots.default?.()}
      </ElButton>
    )
  }
})

export default Button

3. 全局应用按钮组件

import { ElButton, VanButton } from '@/components'

app.component(ElButton.name as string, ElButton)
app.component(VanButton.name as string, VanButton)