VUE 按钮防抖自定义指令
按钮点击防抖
防止用户一直点击,实现按钮点击防抖
这个防抖只会在狂点的第一次的时候执行 和 最后一次执行
// 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