zoukankan      html  css  js  c++  java
  • vue 防抖节流函数——组件封装

    防抖(debounce)

    所谓防抖,就是指触发事件后在 n 秒内函数只能执行一次,如果在 n 秒内又触发了事件,则会重新计算函数执行时间。

    节流(throttle)

    所谓节流,就是指连续触发事件但是在 n 秒中只执行一次函数。节流会稀释函数的执行频率。

    就相当于,一个水龙头在滴水,可能一次性会滴很多滴,但是我们只希望它每隔 500ms 滴一滴水,保持这个频率。即我们希望函数在以一个可以接受的频率重复调用。

    vue 封装utils.js

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

    然后我们在main.js入口文件里面全局注册一下

    import Debounce from '@/config/debounce'
    
    Vue.component('Debounce',Debounce)

    使用方法

    <!--当是isDebounce时表示是防抖函数,!isDebounce是节流函数,time是执行时间间隔-->
        <Debounce :time='1000' isDebounce>
            <button  @click='btn'>btn</button>
        </Debounce>

    转载:https://juejin.im/post/5db114c3e51d452a1c03e25b

  • 相关阅读:
    CSS 实现隐藏滚动条同时又可以滚动
    在vue项目中的axios使用配置记录
    QS:vue中qs的使用
    Electron 无边框窗口最大化最小化关闭功能
    CSS样式表能否控制文字禁止选择,复制, 焦点
    yarn 在Vue框架中的常用命令
    Vue 实现左边导航栏且右边显示具体内容(element-ui)
    Vuex 存储||获取后台接口数据
    软件工程第二周开课介绍
    返回一个整数数组中最大子数组的和 (非环状 和环状)
  • 原文地址:https://www.cnblogs.com/yhhBKY/p/11798093.html
Copyright © 2011-2022 走看看