VUI创建日志(二)——防抖节流组件的实现

时间:2022-07-26
本文章向大家介绍VUI创建日志(二)——防抖节流组件的实现,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

1. 项目实现介绍

vue 项目搭建参考《Webpack4 搭建 Vue 项目》

文档使用 vuepress, 官方文档 vuepress.vuejs.org

发布文档 github pages + gh-page

项目地址 github.com/zxpsuper/vu…

文档地址 zxpsuper.github.io/vui-vue

组件地址 zxpsuper.github.io/vui-vue/com…

处于自我摸索阶段,期待留下您的宝贵意见!

2. Throttle 组件的实现

  1. 首先,写一个防抖节流的通用函数
/**
 * @param {function} func 执行函数
 * @param {number} time 防抖节流时间
 * @param {boolean} isDebounce 是否为防抖组件
 * @param {this} ctx this 的指向
*/
const debounce = (func, time, isDebounce, ctx) => {
    var timer, lastCall, rtn;
    if (isDebounce) {
        rtn = (...params) => {
            if (timer) clearTimeout(timer);
            timer = setTimeout(() => {
                func.apply(ctx, params);
            }, time);
        };
    } else {
        rtn = (...params) => {
            const now = new Date().getTime();
            if (now - lastCall < time && lastCall) return;
            lastCall = now;
            func.apply(ctx, params);
        };
    }
    return rtn;
};
复制代码
  1. 使用抽象组件
export default {
    name: 'Throttle',
    abstract: true,
    props: {
        time: {
            type: Number,
            default: 800,
        },
        events: {
            type: String,
            default: 'click',
        },
        isDebounce: {
            type: Boolean,
            default: false,
        },
    },
    created() {
        this.eventKeys = this.events.split(','); // 分隔事件
        this.originMap = {}; // 储存事件,用于重新render时与子事件的对比
        this.debouncedMap = {}; // 储存防抖节流事件
    },
    render() {
        const vnode = this.$slots.default[0];
        this.eventKeys.forEach(key => {
            const target = vnode.data.on[key];
            if (target === this.originMap[key] && this.debouncedMap[key]) {
                vnode.data.on[key] = this.debouncedMap[key];
            } else if (target) {
                this.originMap[key] = target;
                this.debouncedMap[key] = debounce(
                    target,
                    this.time,
                    this.isDebounce,
                    vnode
                );
                vnode.data.on[key] = this.debouncedMap[key]; // 重写子组件的事件
            }
        });
        return vnode;
    },
};

复制代码

3. 使用组件

需全局或者组件内注册一下,这里只展示全局注册代码:

Vue.component("Throttle", Throttle);

使用方法:

<Throttle :time="5000"  isDebounce>
    <span @click="decounceFunction">
        <Button color="purple" light>防抖按钮Button>
    span>
Throttle>
复制代码

4. 存在问题与解决方法

当页面元素在防抖节流时间内发生了更新(渲染)(可以用定时器修改页面,如页面倒计时),那么此组件会重新执行一遍

this.debouncedMap[key] = debounce(target,this.time,this.isDebounce,vnode);

导致防抖节流失效,目前的解决方法是在此组件的子元素添加 v-once,如下:

<Throttle :time="5000"  isDebounce>
    <span @click="decounceFunction" v-once>
        <Button color="purple" light>防抖按钮Button>
    span>
Throttle>
复制代码

可解决此问题,有更好的方法请在评论区留言

5. 完整代码

/*
 * @descript: 防抖节流组件,前提是页面在等待时间内无其他渲染方可使用,重新渲染导致 debounce() 函数不断重置
 * @Author: super
 * @Date: 2019-04-09 14:21:18
 * @Last Modified by: super
 * @Last Modified time: 2019-10-24 16:37:43
 */

const debounce = (func, time, isDebounce, ctx) => {
    var timer, lastCall, rtn;
    if (isDebounce) {
        rtn = (...params) => {
            if (timer) clearTimeout(timer);
            timer = setTimeout(() => {
                func.apply(ctx, params);
            }, time);
        };
    } else {
        rtn = (...params) => {
            const now = new Date().getTime();
            if (now - lastCall < time && lastCall) return;
            lastCall = now;
            func.apply(ctx, params);
        };
    }
    return rtn;
};

export default {
    name: 'Throttle',
    abstract: true,
    props: {
        time: {
            type: Number,
            default: 800,
        },
        events: {
            type: String,
            default: 'click',
        },
        isDebounce: {
            type: Boolean,
            default: false,
        },
    },
    created() {
        this.eventKeys = this.events.split(',');
        this.originMap = {};
        this.debouncedMap = {};
    },
    render() {
        const vnode = this.$slots.default[0];
        this.eventKeys.forEach(key => {
            const target = vnode.data.on[key];
            if (target === this.originMap[key] && this.debouncedMap[key]) {
                vnode.data.on[key] = this.debouncedMap[key];
            } else if (target) {
                this.originMap[key] = target;
                this.debouncedMap[key] = debounce(
                    target,
                    this.time,
                    this.isDebounce,
                    vnode
                );
                vnode.data.on[key] = this.debouncedMap[key];
            }
        });
        return vnode;
    },
};

复制代码

总结

本文是对render及抽象组件的使用总结,若有错误,望指出共同进步。