分页功能一般是后台实现,前端请求就完事了。但是偶有情况…那也很无奈!数据少的情况,前端可做!数据多了,还是得建议后台来做!!
【注】我这里其实主要用的是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,可以理解成可分页数😆 那我们每次无论是下拉,还是上滑加载,只需每次根据下标累加,取出每项元素,然后合并到一个新的数组里面,也是可以实现按你要求每次加载几条数据😆。