utils/debounce.js
export function debounce(fn, delay = 500) {
let timer = null
return function (...args) {
if (timer) {
clearTimeout(timer)
}
timer = setTimeout(() => {
fn.apply(this, args)
}, delay)
}
}
main.js 定义全局化指令
import {
createApp } from 'vue'
import App from './App.vue'
import {
debounce } from './utils/debounce'
const app = createApp(App)
app.directive('debounce', {
mounted(el, binding) {
const {
value, arg } = binding
const debouncedFn = debounce(value, arg)
el.addEventListener('click', debouncedFn)
},
beforeUnmount(el, binding) {
const {
value } = binding
el.removeEventListener('click', value)
}
})
app.mount('#app')
指令的使用
<template>
<button v-debounce="handleInput" :delay="500">无参</button>
<button v-debounce="() => handleInput2(1, 2)" :delay="500">传参</button>
</template>
<script>
export default{
methods: {
handleInput(){
console.log('防抖指令的使用');
},
handleInput2(v1, v2){
console.log('接收参数', v1,v2);
},
}
}
</script>