懒加载数据列表

后端返回大量数据,前端进行懒加载显示

<template>
  <div>
    <ul class="info" id="info" @scroll="onScroll">
      <li v-for="(item, index) in displayList" :key="index">{{ item }}</li>
      <li class="tip" v-if="loading">加载中...</li>
      <li class="tip" v-else>没有更多了</li>
    </ul>
  </div>
</template>
<script>
import _throttle from 'lodash/throttle'
export default {
  data() {
    return {
      list: [], // 原数据列表
      displayList: [],// 展示数据列表
      loading: true,  // 控制下拉显示文字
      page: 1, // 当前显示0~29
      max: 1 // 最多显示多少页码
    }
  },
  created() {
    for (let i = 0; i < 301; i++) {
      this.list.push(this.list.length + 1)
      this.max = Math.ceil(this.list.length / 30)
      this.displayList = this.list.slice((this.page - 1) * 30, this.page * 30)
      console.log(this.max)
    }
  },
  methods: {
    // 滚动触发事件
    onScroll: _throttle(function () {
      var info = document.getElementById('info')
      var scrollTop = info.scrollTop
      var clientHeight = info.clientHeight
      var scrollHeight = info.scrollHeight
      if (scrollHeight - clientHeight < scrollTop + 20) {
        if (this.displayList.length >= this.list.length) {
          this.loading = false
          return
        } else {
          this.addList()
        }
      }
    }, 2000),
    // 改变展示数据
    addList() {
      this.loading = true
      setTimeout(() => {
        if (this.page < this.max) {
          this.page++
          const info = this.list.slice((this.page - 1) * 30, this.page * 30)
          this.displayList = [...this.displayList, ...info]
        }
      }, 1000)
    }
  }
}
</script>
<style scoped>
ul {
  width: 300px;
  height: 550px;
  overflow: auto;
  list-style: none;
  margin: 10px;
  padding: 0;
  border: 1px solid gray;
  overflow-anchor: none;
}
li {
  line-height: 30px;
}
li:nth-of-type(odd) {
  margin: 0;
  padding: 0;
  background: rgb(228, 245, 245);
}
li:last-child {
  background: white;
}
.tip {
  color: gainsboro;
  text-align: center;
}
</style>

// 如果上述代码无法运行,请先安装lodash
命令:npm i --save lodash

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值