vue 中防抖和节流封装和使用

vue 中防抖和节流封装和使用,第1张

1、封装。在utils新建throttle.js 
// 节流
export function _throttle(fn, interval = 1000) {
    let last;
    let timer;
    return function () {
        let th = this
        let args = arguments;
        let now = + new Date();
        if (last && now - last < interval) {
            clearTimeout(timer);
            timer = setTimeout(function () {
                last = now;
                fn(th, args);
            }, interval);
        } else {
            last = now;
            fn.apply(th, args);
        }
    }
}
// 防抖
export function _debounce(fn, delay = 1000) {
    let timer;
    return function () {
        let th = this;
        let args = arguments;
        if (timer) {
            clearTimeout(timer);
        }
        timer = setTimeout(function () {
            timer = null;
            fn.apply(th, args);
        }, delay);
    };
}

2、使用。在有需要的页面引入

import { _debounce, _throttle } from '@/utils/throttle'

methods: {
  onSearch : _throttle( function (val){
        // 业务代码

  }),
}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1322216.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-12
下一篇 2022-06-12

发表评论

登录后才能评论

评论列表(0条)

保存