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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM