Vue简单实现滚动究竟部加载数据

作者 : 开心源码 本文共1896个字,预计阅读时间需要5分钟 发布时间: 2022-05-13 共205人阅读

最近想写个网站需要滚动加载的功能,用了element的infinite-scroll感觉局限太大,干脆自己写一个,功能如下

image


原理

vue实现滚动究竟部加载数据的原理是监听页面滚动,当页面滚动究竟部的时候,前台从后台获取分好页的数据加入到datas[]数组中,进行渲染,就实现了滚动加载的功能


先理解几个关键词:

(1)滚动条到顶部的位置:scrollTop

(2)当前窗口内容可视区:windowHeight

(3)滚动条内容的总高度:scrollHeight

触发监听滚动条的函数是:

window.onscroll = ()=>{...}
判断究竟部的等式: scrollTop+windowHeight=scrollHeight;


实现

我用的是vue脚手架搭的项目,都写在App.vue文件里,代码如下

App.vue文件

<template>  <div id="app">    <div class="list" v-for="(data,index) in datas" :key="index">        {{data}}    </div>  </div></template><script>export default {  name: 'app',  data() {    return {      datas:[],      testdatas:['1','2','3','4','5'],  //初始加载测试数据      count:5,  //默认加载数量      isAchiveBottom: false //滚动条能否究竟部标志    }  },  created() {    //使用window.onscroll = function(){}this指向出现问题    //故应该使用箭头函数,由于箭头函数无this,会从上一级找,故会找到vue实例的this    window.onscroll = () => {      //变量scrollTop是滚动条滚动时,距离顶部的距离      var scrollTop =        document.documentElement.scrollTop || document.body.scrollTop;      //变量windowHeight是可视区的高度      var windowHeight =        document.documentElement.clientHeight || document.body.clientHeight;      //变量scrollHeight是滚动条的总高度      var scrollHeight =        document.documentElement.scrollHeight || document.body.scrollHeight;      //滚动条究竟部的条件(距底部20px时触发加载)      if (        scrollTop + windowHeight >= scrollHeight - 20 &&        !this.isAchiveBottom &&        !this.noMore      ) {        // console.log(        //   "距顶部" +        //     scrollTop +        //     "可视区高度" +        //     windowHeight +        //     "滚动条总高度" +        //     scrollHeight        // );        this.isAchiveBottom = true;        //延时触发数据加载        setTimeout(() => {          //后台需要进行分页,而后前台从后台拿来实现滚动加载          //这里利用数组push来模拟从后台拿到的数据          this.datas.push("test");          this.isAchiveBottom = false;        }, 500);      }    };  },  beforeMount() {    // 在页面挂载前就发起请求    this.getInitial();  },  methods: {    getInitial(){      for (var i = 0; i < this.count; i++) {        this.datas.push(this.testdatas[i]);      }    }  },}</script><style>#app {  font-family: 'Avenir', Helvetica, Arial, sans-serif;  -webkit-font-smoothing: antialiased;  -moz-osx-font-smoothing: grayscale;  text-align: center;  color: #2c3e50;  margin-top: 60px;}.list{  background-color: #d2d2d2;  border-radius: 3px;  width: 50%;  height: 150px;  line-height: 150px;  margin: 0 auto 20px auto;}</style>

github项目地址

rongliangtang/vue-infinite-scroll-demo.git

说明
1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长!
2. 分享目的仅供大家学习和交流,您必须在下载后24小时内删除!
3. 不得使用于非法商业用途,不得违反国家法律。否则后果自负!
4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解!
5. 如有链接无法下载、失效或广告,请联系管理员处理!
6. 本站资源售价只是摆设,本站源码仅提供给会员学习使用!
7. 如遇到加密压缩包,请使用360解压,如遇到无法解压的请联系管理员
开心源码网 » Vue简单实现滚动究竟部加载数据

发表回复