1. 处理点击指定元素之外的工具,推荐在mounted及以后的生命周期中执行
/**
* [装饰器]处理点击指定元素之外的工具,推荐在mounted及以后的生命周期中执行
* @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. 防抖动函数
/**
* [装饰器]防止抖动
* @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;
};
}
网友评论