站三界导航
首页 JS代码js常用公共方法-防抖节流插槽版(可用于防止重复提交)

js常用公共方法-防抖节流插槽版(可用于防止重复提交)

  • JS代码
  • 来源:站三界导航
  • 58阅读
  • 2022-09-10

/**
 * 防抖函数(可用于防止重复提交), 就是指触发事件后在 n 秒内函数只能执行一次
 * 节流函数, 就是指连续触发事件但是在 n 秒中只执行一次函数。节流会稀释函数的执行频率
 *
 * @param func 执行函数
 * @param time 执行时间间隔
 * @param isDebounce 是否防抖或者节流
 * @param ctx event
 */
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: 'Debounce',
    abstract: true,
    props: {
        time: {
            type: Number,
            default: 800,
        },
        events: {
            type: String,
            default: 'click',
        },
        isDebounce: {
            type: Boolean,
            default: true,
        },
    },
    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;
    },
};
使用方法:
 <Debounce :time='200' >
            <el-button @click.native="handleUserLogin">登录</el-button>
        </Debounce>
main.js
 
// 防抖 or 节流
import Debounce from '@/utils/debounce'
Vue.component('Debounce', Debounce)

本文结束
本文来自投稿,不代表站三界导航立场,如若转载,请注明出处:https://www.zhansanjie.com/article/details/10193.html

版权声明:

1、本文系转载,版权归原作者所有,旨在传递信息,不代表看本站的观点和立场。

2、本站仅提供信息发布平台,不承担相关法律责任。

3、若侵犯您的版权或隐私,请联系本站管理员删除。

4、本文由会员转载自互联网,如果您是文章原创作者,请联系本站注明您的版权信息。

分享
站三界导航
本站声明:本站严格遵守国家相关法律规定,非正规网站一概不予收录。本站所有资料取之于互联网,任何公司或个人参考使用本资料请自辨真伪、后果自负,站三界导航不承担任何责任。在此特别感谢您对站三界导航的支持与厚爱。