前端分页加载数据方法?

分页功能一般是后台实现,前端请求就完事了。但是偶有情况...那也很无奈!数据少的情况,前端可做!数据多了,还是得建议后台来做!!

【注】我这里其实主要用的是Array.slice(start, end)方法!直接上代码,不啰嗦!
【效果】
请添加图片描述
代码:
html:

<template>
  <view>
    <button @click="PageLoad">点击加载</button>
  </view>
</template>

js:

<script>
export default {
	data() {
		return {
			mokeData: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
			curPage: 0, // 当前页
			perPage: 3,
			start: 0,
			end: 0,
			data: []
		}
	},
	methods: {
		PageLoad() {
			this.curPage++
			this.pageRequire(this.mokeData, this.curPage, this.perPage, 'asc')
			console.error(this.data);
		},
		// sort 排序类型 desc倒序 / asc正序
		pageRequire(arr, curPage, perPage, sort) {
			let totalLen = arr.length // 数据长度
			// let start = 0;
			// let end = 0;
			let resArr = []
  		let totalPage = Math.ceil(totalLen / perPage) // 总分页数
  		totalPage = totalPage - curPage
  		let curTotalNum = totalLen - this.end
  		if (sort === 'asc') {
				// 阻止
    		if (curTotalNum <= 0) {
    		  alert('没有更多啦~')
    		  return 
    		}
  		  totalPage = totalPage - curPage
  		  this.end = curPage * perPage
  		  resArr = arr.slice(this.start, this.end)
				this.data = [...this.data, ...resArr]
  		  // console.log(resArr);
  		  this.start = this.start + perPage
  		} else {
				// 阻止
   			if (totalPage < 0) {
   			  alert('没有更多啦~')
   			  return 
   			}
  		  this.start = totalLen - (perPage * curPage) // 起止
  		  this.end = totalLen - ((curPage - 1) * perPage) // 终止
  		  if (this.start <= 0) this.start = 0;
  		  resArr= arr.slice(this.start, this.end)
				this.data = [...resArr, ...this.data]
  		  // console.log(resArr);
  		}
		}
	}
}
</script>

还有一种取巧方法:

/**
	 * array: 处理数组
	 * groupNum: 分几组
	 */
	dealArray(array: Array<any>, groupNum: number) {
		let temp:any = []
		for(let i = 0, len = array.length; i < len; i += groupNum) {
			temp.push(array.slice(i, i + groupNum))
		}
		return temp
	}

思路:我们可以将拿到所有数据数组分成几个小数组,这里的小数组你可以理解成每页要展示的条数😆!
结构如下:
在这里插入图片描述
这里的length,可以理解成可分页数😆
那我们每次无论是下拉,还是上滑加载,只需每次根据下标累加,取出每项元素,然后合并到一个新的数组里面,也是可以实现按你要求每次加载几条数据😆

posted @   -Sirius-  阅读(521)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示