vue3、ts、Element-plus按钮防抖自定义指令

按钮点击防抖

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

	// 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 的自定义指令。

vue 指令

vue 指令可以全局注册 或者局部注册,这里我选择了全局注册。

在 src/utils 文件夹中 新增加了 directive 文件夹, 新建一个叫 btnAntiShake.ts 的文件

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')
	
	// 也可以直接在main.ts 中注册指令
  // 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);
  //     })
  //   }
  // })

使用

这个 confirmBtn 方法就是 上面的 binding.value
在这里插入图片描述

  • 3
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值