函数定义
//添加自定义防抖指令
export function addDebounceDirective(Vue) {
Vue.directive('debounce-click', {
bind(el, binding) {
const { value, arg } = binding;
const callback = typeof value === 'function' ? value : value.handler;
const delay = arg ? parseInt(arg) : 300;
const debouncedCallback = Vue.prototype.$debounce(callback, delay);
el.addEventListener('click', debouncedCallback);
},
unbind(el, binding) {
const { value } = binding;
const callback = typeof value === 'function' ? value : value.handler;
el.removeEventListener('click', callback);
},
});
}
//添加自定义节流指令
export function addThrottleDirective(Vue) {
Vue.directive('throttle-click', {
bind(el, binding) {
const { value, arg } = binding;
const callback = typeof value === 'function' ? value : value.handler;
const delay = arg ? parseInt(arg) : 300;
const debouncedCallback = Vue.prototype.$throttle(callback, delay);
el.addEventListener('click', debouncedCallback);
},
unbind(el, binding) {
const { value } = binding;
const callback = typeof value === 'function' ? value : value.handler;
el.removeEventListener('click', callback);
},
});
}
引入
//自定义防抖节流指令
import { debounce,throttle } from 'lodash';
Vue.prototype.$debounce = debounce;
Vue.prototype.$throttle = throttle;
import {addDebounceDirective,addThrottleDirective} from '@xt/utils/util'
addDebounceDirective(Vue)
addThrottleDirective(Vue)
使用
<el-button class="normal-btn" type="primary" v-debounce-click="search">搜索</el-button>