utils/debounce.js
export function debounce(fn, delay = 500) {
let timer = null
return function () {
const args = arguments
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>
</template>
<script>
export default{
methods: {
handleInput(){
console.log('防抖指令的使用');
},
}
}
</script>