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