防抖和节流

68 篇文章 2 订阅
23 篇文章 1 订阅

之前代码:

滑动右侧A-Z导航条

handlerTouchMove(e) {
  if (this.touchStatus) {     
      const touchY = e.touches[0].clientY - 79;
      const letterIndex = Math.floor((touchY - this.startY) / 20);
      if(letterIndex >= 0 && letterIndex < this.firstLetterList.length){
		this.$emit("change-letter", this.firstLetterList[letterIndex]);
	  }  
  }
},

防抖:

handleTouchMove(e){
    //如果16ms还有操作就会再次触发touchMove,然后清除timer,重新计时,
    //所以只有保证16ms内不滑动,不清除timer才会执行$emit操作
    if(this.touchStatus){
        if(this.timer){
            clearTimeout(this.timer)
        }
        this.timer = setTimeout(() => {
            //ref属性,在v-for里面循环生成的时候,是个Arrray,如果要获取dom元素,要用this.$refs[ref值][0]这样的形式
            const startY  = this.$refs['A'][0].offsetTop //3.拿到第一个元素距离顶部高度
            const touchY = e.touches[0].clientY-79 //4.拿到手指触动的位置
            const index = Math.floor((touchY-startY)/20) //5.得到字母下标
            if(index>=0 && index<this.letters.length){ //6.判断index范围
                this.$emit('change',this.letters[index])
            }
        },16)       
    }
}

节流:

if (this.touchStatus) {

    let flag = true

    if (!flag){
        return flag = false
    } 

    setTimeout(() => { // 函数节流提升性能

      const startY = this.$refs['A'][0].offsetTop
      const touchY = e.touches[0].clientY - 79 
      const index = Math.floor((touchY - this.startY) / 20) 

      if (index >= 0 && index < this.latters.length) {
        this.$emit('change', this.latters[index]) 
      }

      flag = true

    }, 16)

}

参考链接:
https://coding.imooc.com/learn/questiondetail/142413.html
https://coding.imooc.com/learn/questiondetail/94705.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值