1. 處理點(diǎn)擊指定元素之外的工具,推薦在mounted及以后的生命周期中執(zhí)行
/**
* [裝飾器]處理點(diǎn)擊指定元素之外的工具吨枉,推薦在mounted及以后的生命周期中執(zhí)行
* @param offscaleElRef 指定元素的ref值
*/
export function ClickOutside(offscaleElRef: string): any {
return (
target: Object,
propertyKey: string,
propertyDecorator: PropertyDescriptor
): PropertyDescriptor => {
const methods = propertyDecorator.value;
propertyDecorator.value = function(this: any, ...args: any): void {
const offscaleEl = this.$refs[offscaleElRef];
if (offscaleEl && offscaleEl.contains) {
document.addEventListener('click', event => {
if (!event || !event.target) return;
const clickEl = event.target as HTMLElement;
const clickSelf = offscaleEl.contains(clickEl);
if (!clickSelf) {
methods.call(this, ...args);
}
});
}
};
return propertyDecorator;
};
}
2. 防抖動(dòng)函數(shù)
/**
* [裝飾器]防止抖動(dòng)
* @param delay 延遲
*/
export function Debounce(delay = 300): any {
return (
target: Object,
propertyKey: string,
propertyDecorator: PropertyDescriptor
): PropertyDescriptor => {
const methods = propertyDecorator.value;
let timer: number | null = null;
propertyDecorator.value = function(...args: any): void {
timer && clearTimeout(timer);
timer = setTimeout(methods.bind(this, ...args), delay);
};
return propertyDecorator;
};
}