Vue学习笔记-项目开发3.8函数节流(城市列表页面优化)

1、减少计算
反复计算顶部与A字母标签的距离 这个抽取出来只在页面加载的时候计算一次即可

  data () {
    return {
      touchStatus: false,
	  // 这里添加一个变量
      startY: 0,
    }
  },
  //页面一开始的时候cities变量是空值。然后通过ajax获取到数据的时候并加载至页面的时候触发生命周期函数updated 这时候做顶部与字母A标签的距离。
  updated () {
    this.startY = this.$refs['A'][0].offsetTop
  },
 
 
handleTouchMove (e) {
      if (this.touchStatus) {
// 这条删掉 
        const startY = this.$refs['A'][0].offsetTop
        const touchY = e.touches[0].clientY - 79
//这里讲startY 改成 this.startY    
        const index = Math.floor((touchY - startY) / 20)
        if (index >= 0 && index < this.letters.length) {
          this.$emit('change', this.letters[index])
        }
      }
    },

2、函数节流
目前的代码是拇指在字母列表上滑动的时候,实时计算距离。但是这样很浪费性能。计算频率太高了。所以做一个计时器。在一定时间内才计算一次。

  data () {
    return {
      touchStatus: false,
      startY: 0,
	  // 添加一个计时器变量
      timer: null
    }
  },
 
handleTouchMove (e) {
      if (this.touchStatus) {
		// 每16毫秒计算一次。 这样可以减少很多的计算工作,同时不影响功能
		//如果有计时器了的话  清掉它。 避免缓存。
        if (this.timer) {
          clearTimeout(this.timer)
        }
        this.timer = setTimeout( () => {
          const touchY = e.touches[0].clientY - 79
          const index = Math.floor((touchY - this.startY) / 20)
          if (index >= 0 && index < this.letters.length) {
            this.$emit('change', this.letters[index])
          }
        }, 16)
      }
    },
    handleTouchEnd () {
      this.touchStatus = false
    }
  }
}
发布了24 篇原创文章 · 获赞 1 · 访问量 547

猜你喜欢

转载自blog.csdn.net/Kasey_L/article/details/104700008