vue3按钮防抖自定义指令

按钮点击防抖

防止用户一直点击,实现按钮点击防抖
这个防抖只会在狂点的第一次的时候执行 和 最后一次执行

    // HTML
    <template>
        <el-button @click="clickShake">防抖</el-button>
    </template>
    
    // javaScript
    <script lang="ts">
    import { defineComponent } from 'vue'
    export default defineComponent({
        setup() {
            let timer: NodeJS.Timeout | null = null

            const fn = () => {
                console.log('我是要执行的函数')
            }
            const clickShake = () => {
                let firstClick: Boolean = !timer;
                if (firstClick) fn()
                if (timer) clearTimeout(timer)
                timer = setTimeout(() => {
                    timer = null
                    if (!firstClick) fn()
                }, 2000)
            }
            
            return {
                fn,
                clickShake
            }
        }
    })
    </script>

vue 指令

import { App, DirectiveBinding } from 'vue'

export default (app: App<Element>) => {
  app.directive('btnAntiShake', {
    mounted(el: HTMLElement, binding: DirectiveBinding) {
      let timer: NodeJS.Timeout | null = null
      el.addEventListener('click', () => {
      let firstClick: Boolean = !timer;
  
      if (firstClick) {
        binding.value()
      }
      if (timer) {
        clearTimeout(timer)
      }
      timer = setTimeout(() => {
        timer = null
        if (!firstClick) {
          binding.value()
        }
      }, 1000);
      })
    }
  })
}

在 main.ts 中 引入、注册

import btnAntiShake from './utils/directive/btnAntiShake'

  const app = createApp(App)
  // button 防抖
  app.use(btnAntiShake)
  app.mount('#app')

使用

  <el-button type="primary" v-debounce="handleSubmit">确定</el-button>
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容