• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

Vue方法使用防抖和节流

武飞扬头像
1024小神
帮助1

最简单的一种:直接使用lodash封装好的工厂函数:

  1.  
    // _为自己命名
  2.  
    import _ from 'lodash'
  3.  
     
  4.  
    // debounce 防抖
  5.  
    方法名:_.debounce(function(传递参数){
  6.  
    //具体方法
  7.  
    },300),
  8.  
     
  9.  
    // throttle 节流
  10.  
    方法名:_.throttle(function(传递参数){
  11.  
    //具体方法
  12.  
    },300),

会返回一个新的函数,直接在vue的methods中使用:

  1.  
    methods: {
  2.  
    // 改变场数
  3.  
    changefield: _.debounce(function(_type, index, item) {
  4.  
    // do something ...
  5.  
    }, 300)
  6.  
    }

或者:

  1.  
    methods:{
  2.  
    queryList() {
  3.  
    return _.debounce(() => {
  4.  
    // 函数体
  5.  
    }, 500)()
  6.  
    }
  7.  
    }

自己封装一个防抖和节流的工具类:

  1.  
    // 防抖
  2.  
    export function _debounce(fn, delay) {
  3.  
     
  4.  
    var delay = delay || 200;
  5.  
    var timer;
  6.  
    return function () {
  7.  
    var th = this;
  8.  
    var args = arguments;
  9.  
    if (timer) {
  10.  
    clearTimeout(timer);
  11.  
    }
  12.  
    timer = setTimeout(function () {
  13.  
    timer = null;
  14.  
    fn.apply(th, args);
  15.  
    }, delay);
  16.  
    };
  17.  
    }
  18.  
    // 节流
  19.  
    export function _throttle(fn, interval) {
  20.  
    var last;
  21.  
    var timer;
  22.  
    var interval = interval || 200;
  23.  
    return function () {
  24.  
    var th = this;
  25.  
    var args = arguments;
  26.  
    var now = new Date();
  27.  
    if (last && now - last < interval) {
  28.  
    clearTimeout(timer);
  29.  
    timer = setTimeout(function () {
  30.  
    last = now;
  31.  
    fn.apply(th, args);
  32.  
    }, interval);
  33.  
    } else {
  34.  
    last = now;
  35.  
    fn.apply(th, args);
  36.  
    }
  37.  
    }
  38.  
    }
学新通

然后在vue中引入并使用:

  1.  
    import { _debounce } from "..."
  2.  
     
  3.  
     
  4.  
     
  5.  
     
  6.  
    methods: {
  7.  
    // 改变场数
  8.  
    changefield: _debounce(function(_type, index, item) {
  9.  
    // do something ...
  10.  
    }, 200)
  11.  
    }

学新通

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhiegcah
系列文章
更多 icon
同类精品
更多 icon
继续加载