数据懒加载

80 阅读1分钟

通过滚动事件动态渲染页面数据

主要思路:通过判断页面是否触底,对数据进行修改,渲染页面

 <div class="container"  ref="container" @scroll="scrollEvent($event)">
        <div class="list"  v-for="(item,index) in listnewData" :key="index" >
            {{item}}
        </div>
  </div>
  
  
  <script>
export default {
  name: 'Ho-me',
  data () {
    return {
      bookid: '6815554341034789896',
      listData: [], // 列表总总数据
      listnewData: [], // 需要渲染的数据
      start: 0,  //开始的索引
      end: null   //结束的索引
    }
  },
  async mounted () {
  //发起请求,
    const result = await this.$API.reqBookItem(this.bookid)
    //将返回回来的数据赋值给listData
    this.listData = result.data.allItemIds
    //对listData进行切割,重新赋值,这个新的数据就是页面需要渲染的数据
    this.listnewData = this.listData.slice(0, 10)
  },
 
  methods: {
    scrollEvent (e) {
      const scrollTop = this.$refs.container.scrollTop
      this.start = Math.floor(scrollTop / 20)
      this.end = this.start + 10
      const scrollHeight = this.$refs.container.scrollHeight
      // clientHeight是元素可视区域的高度
      const as = this.$refs.container.clientHeight
      if (scrollTop + as >= scrollHeight) {
        //通过索引切割listData数据并返回一个新数组
        const a = this.listData.slice(this.start, this.end)
        //循环新数据,对需要渲染的列表数据进行修改
        a.forEach((item) => {
          this.listnewData.push(item)
        })
      }
    }
  }
}
</script>

scroll事件

给需要监听的盒子添加scroll事件,在添加scroll事件的时候必须要给盒子加上高度和overflow:scroll,不然滚动事件是不会生效的

如何判断页面是否触底

通过scrollTop + clientHeight >= scrollHeight来判断页面是否触底, scrollTop是盒子滚动的距离,clientHeight是盒子可视区域的距离,scrollHeight是盒子内容的总高度,如果盒子滚动的距离+可视区域的距离>=盒子内容的高度,这个时候就代表页面触底了,当页面触底的时候,就重新渲染页面