日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 综合教程 >内容正文

综合教程

vue 防抖节流函数——组件封装

發布時間:2023/12/15 综合教程 28 生活家
生活随笔 收集整理的這篇文章主要介紹了 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

總結

以上是生活随笔為你收集整理的vue 防抖节流函数——组件封装的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。