滚动底部和顶部加载数据

338 阅读1分钟
   <div id="scrollDiv" ref="scrollPosition">
    </div>
<script>
data() {
   return {
      isScrollBottom: false, // 是否滚动底部加载
      isScrollTop: true, // 是否滚动顶部加载
      pages:10,//当前总页数
      currentPage:0//当前处于第几页
   }
},
mounted() {
    // 获取指定元素
    const scrollview = this.$refs.scrollPosition;
    // 添加滚动监听,该滚动监听了拖拽滚动条
    scrollview.addEventListener("scroll", this.handleScroll, true);
  },
  beforeDestroy() {
    // 获取指定元素
    const scrollview = this.$refs.scrollPosition;
    // 移除监听
    scrollview.removeEventListener("scroll", this.handleScroll, false);
  },
  methods: {
      handleScroll() {
          let scrollTop = document.querySelector("#scrollDiv").scrollTop;
          var windowHeight =
            document.documentElement.clientHeight || document.body.clientHeight;
          let scrollHeight = document.querySelector("#scrollDiv").scrollHeight;
          // 滚动条到底部
          if (scrollTop + windowHeight === scrollHeight && this.isScrollBottom) {
            if (this.currentPage>this.pages) return;
             this.currentPage++;
            this.isScrollBottom = false;
            this.find(0); // 滚到底部加载数据
          }
          // 滚动条到顶部
          if (scrollTop === 0 && this.isScrollTop) {
            if (this.currentPage =<1) return;
            this.currentPage++;
            this.isScrollTop = false;
            this.find(1); // 滚动到顶部加载
          }
        },
        find(check){
           setTimeout(() => {
          // 底部加载数据
          if (check === 0) {
            this.$refs.scrollPosition.scrollTop -=
              70 * res.data.data.records.length;  //根据自身设定加载数据后需要离底部多远
            this.isScrollBottom = true;
          }
          //顶部加载数据
          if (check === 1) {
            this.$refs.scrollPosition.scrollTop +=  /根据自身设定加载数据后需要离定部多远
              70 * res.data.data.records.length;  
            this.isScrollTop = true;
              }
            }, 200);
        }
        
  }

</script>