在utils/index.js 文件中
// 防抖 立即执行 function debounce(fn, arg) { // delay = delay || 1000; let delay = 1000; let timeout; return function() { let context = this; if (timeout) clearTimeout(timeout); let callNow = !timeout; timeout = setTimeout(() => { timeout = null; }, delay); if (callNow) fn.apply(context, arg); }; } export { debounce };
src/directive/index.js 自定义指令:
import Vue from 'vue';import { debounce } from '@/utils';
Vue.directive('debounce', { bind(el, binding) { const [fn, ...args] = binding.value; el.addEventListener('click', debounce(fn, args)); }, unbind(el, binding) { const [fn, ...args] = binding.value; el.removeEventListener('click', debounce(fn, args)); } });
使用:
<el-button v-debounce="[handleDownload]">下载模版</el-button> // 要执行的函数 handleDownload() { console.log() },