防抖和节流

之前代码:

滑动右侧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

你可能感兴趣的:(Javascript,Vue,前端)