vue 实现滚动监听加载更多 addEventListener(‘scroll‘, this.handleScroll)

直接上代码:

 mounted() {
    
    
    // 监听滚动事件,然后用handleScroll这个方法进行相应的处理
    window.addEventListener('scroll', this.handleScroll)
  },
  // 离开这个页面销毁滚动条事件,不然会给每一个页面都触发
  beforeDestroy() {
    
    
    window.removeEventListener('scroll', this.handleScroll)
  },
 methods: {
    
    
    handleScroll() {
    
    
      // 设备/屏幕高度
      let clientHeight = document.documentElement.clientHeight || document.body.clientHeight
      // 滚动区域
      let scrollObj = document.getElementsByClassName('content-cent')[0]
      // 滚动区域到头部的距离
      let scrollTop = scrollObj.scrollTop
      // 滚动条的总高度
      let scrollHeight = scrollObj.scrollHeight
      // 滚动条到底部的条件
      if (scrollTop + clientHeight == scrollHeight) {
    
    
        // 滚动区域到头部的距离 + 屏幕高度 = 可滚动的总高度
        this.loadMore()
      }
    }
  }

在这里window.addEventListener('scroll', this.handleScroll)有一个问题,不是所有的都有效的,如果发现不能实现滚动,那么请加上这句话:

window.addEventListener('scroll', this.handleScroll, true)

猜你喜欢

转载自blog.csdn.net/m0_46442996/article/details/110930713
今日推荐