美文网首页
装饰器语法的工具函数 [VUE] + TS 持续更新中

装饰器语法的工具函数 [VUE] + TS 持续更新中

作者: 怪兽难吃素 | 来源:发表于2021-03-31 23:00 被阅读0次

    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;
        };
    }
    

    相关文章

      网友评论

          本文标题:装饰器语法的工具函数 [VUE] + TS 持续更新中

          本文链接:https://www.haomeiwen.com/subject/ksgxkltx.html