首页

vue中实现下拉加载

kkcode
2023-08-18  阅读 231

下拉加载

  1. 监听滚动事件
  2. 滚动到最底部,加载更多
  3. 发送请求,请求成功后,在原来的基础上添加数据
  4. 重新绑定滚动事件
  5. 重新绑定滚动事件
  6. 重复以上操作
  7. 监听滚动事件
  8. 滚动到最底部,加载更多
  9. 发送请求,请求成功后,在原来的基础上添加数据
  10. 重新绑定滚动事件
  11. 重复以上操作

使用codeGeex生成

<template>
  <div id="app">
    <div ref="scrollContainer" @scroll="handleScroll" class="scroll-container">
      <div v-for="(item, index) in items" :key="index">{{ item }}</div>
    </div>
    <button @click="loadMore">Load More</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      items: [],
      isLoading: false
    };
  },
  mounted() {
    this.bindScrollEvent();
  },
  beforeDestroy() {
    this.unbindScrollEvent();
  },
  methods: {
    handleScroll() {
      if (
        !this.isLoading &&
        this.$refs.scrollContainer.scrollHeight -
          this.$refs.scrollContainer.scrollTop ===
          this.$refs.scrollContainer.clientHeight
      ) {
        this.loadMore();
      }
    },
    bindScrollEvent() {
      window.addEventListener('scroll', this.handleScroll);
    },
    unbindScrollEvent() {
      window.removeEventListener('scroll', this.handleScroll);
    },
    loadMore() {
      this.isLoading = true;
      // Send a request to fetch more data
      // Example: fetchMoreData().then((moreItems) => {
      //   this.items = [...this.items, ...moreItems];
      //   this.isLoading = false;
      // });
    }
  }
};
</script>

<style scoped>
.scroll-container {
  overflow-y: auto;
  height: 300px;
  width: 100%;
}
</style>复制代码

一位网友的写法:

created(){
    // 页面创建后先请求一次数据
    this.getDataList();
  },
  mounted(){
    // 监听页面滚动
    window.onscroll=this.pageScroll;
  },
 methods:{
     //请求数据方法
   getDataList(){
     axios.get(`请求路径`).then((res)=>{
      // console.log(res);
      // 使用扩展运算符将新获取的数据添加至原数组
      this.原数据=[...this.原数据,...res.请求到的数据];
    })
   },
  //  页面滚动事件  常做下拉加载内容
  pageScroll(){
    // 获取滚动的距离
    let scrollTop=document.documentElement.scrollTop;
    // 获取滚动的高度(获取整个html的高度)
    let scrollHeight=document.documentElement.scrollHeight;
    // 获取屏幕(浏览器)高度
    let clienHeight=document.documentElement.clientHeight;
    // 滚动的距离 + 屏幕高度 - 内容高度 >= 0 表示滚动到底部了      (下拉加载判断条件)
    if(scrollTop+clienHeight-scrollHeight >=0){
      console.log("我到底了");
      this.offset++;
      //滚动至底部后请求数据
      this.getDataList();
    }
  }
 }复制代码

参考链接:

本文为作者原创文章,转载无需和我联系,但请注明转载链接。 【前端黑猫】