在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));
  },
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值