在Vue中使用Lodash的节流throttle函数

最近有这样的一个应用场景,input输入框中监听用户输入,变化了就发送ajax请求后端数据,以前搜索筛选都是用户手动点击或者回车,现在实时获取,想着最好还是做下节流
lodash官网
吐槽一下,lodash这个文档写的真拉胯,按它的示例,我饭碗早就没了…
在这里插入图片描述

1. 无效的示例(会出错)

methods:{
    
    
    handleFilterTags1(e) {
    
    
      _.throttle(() => {
    
    
        this.ajaxGetTagsAggregation(e);
      }, 200);
    },
    handleFilterTags2(e) {
    
    
      _.throttle(this.ajaxGetTagsAggregation(e), 200);
    },
}

handleFilterTags1中 ajaxGetTagsAggregation方法不会预期执行。
handleFilterTags2控制台会警告和报错但是ajaxGetTagsAggregation能正常执行
看了下源码,应该是返回了一个函数
在这里插入图片描述
盲猜应该是this指向问题

2.我研究调试成功的写法

methods:{
    
    
	// 方式1,唯一的好处就是可以访问Vue全局挂载的lodash
    handleFilterTags(e) {
    
    
      _.throttle(function filterTags() {
    
    
        console.log('调用了---', e, this);
        const params = e ? {
    
     tag_name: e.trim() } : {
    
    };
        this.ajaxGetTagsAggregation(params);
      }, 300).call(this);
    },
    // 方式2, 不用自己修改this指向
    handleFilterTags2: _.throttle(function filterTags(e) {
    
    
      const params = e ? {
    
     tag_name: e.trim() } : {
    
    };
      this.ajaxGetTagsAggregation(params);
    }, 300),
}

throttle还是尽量不要用箭头函数了

3.其它场景

  mounted() {
    
    
    window.addEventListener('scroll', _.throttle(this.scrollBottom, 300));
  },

猜你喜欢

转载自blog.csdn.net/s18438610353/article/details/125928662
今日推荐