js分页实现
分页的基本原理
分页的核心是通过计算当前页码和数据偏移量,从服务器或本地数据中截取对应范围的数据进行展示。通常需要以下参数:当前页码(currentPage)、每页条数(pageSize)、总数据量(total)。
前端分页实现(本地数据)
适用于数据已全部加载到前端的情况:
function paginate(data, currentPage = 1, pageSize = 10) {
const startIndex = (currentPage - 1) * pageSize;
return data.slice(startIndex, startIndex + pageSize);
}
// 示例用法
const allData = [...]; // 原始数据数组
const pageData = paginate(allData, 2, 5); // 获取第2页,每页5条
后端分页实现(API请求)
需要与后端配合,通过参数传递分页信息:
async function fetchPaginatedData(page, size) {
const response = await fetch(`/api/data?page=${page}&size=${size}`);
return response.json();
}
// 示例用法
const { data, total } = await fetchPaginatedData(1, 10);
分页控件实现
常见的分页UI组件实现逻辑:
function renderPagination(total, currentPage, pageSize, container) {
const totalPages = Math.ceil(total / pageSize);
let html = '';
if (currentPage > 1) {
html += `<button class="prev">上一页</button>`;
}
for (let i = 1; i <= totalPages; i++) {
html += `<button class="page ${i === currentPage ? 'active' : ''}">${i}</button>`;
}
if (currentPage < totalPages) {
html += `<button class="next">下一页</button>`;
}
container.innerHTML = html;
// 事件监听
container.addEventListener('click', (e) => {
if (e.target.classList.contains('prev')) {
// 上一页逻辑
} else if (e.target.classList.contains('next')) {
// 下一页逻辑
} else if (e.target.classList.contains('page')) {
// 跳转页码逻辑
}
});
}
性能优化建议
对于大数据量的分页,考虑以下优化方案:
- 虚拟滚动:只渲染可视区域内的数据
- 数据预加载:提前加载相邻页面的数据
- 分页缓存:对已请求过的页面数据进行缓存
完整示例代码
class Pagination {
constructor({ total, pageSize, onChange }) {
this.total = total;
this.pageSize = pageSize;
this.currentPage = 1;
this.onChange = onChange;
}
get totalPages() {
return Math.ceil(this.total / this.pageSize);
}
next() {
if (this.currentPage < this.totalPages) {
this.goTo(this.currentPage + 1);
}
}
prev() {
if (this.currentPage > 1) {
this.goTo(this.currentPage - 1);
}
}
goTo(page) {
this.currentPage = Math.max(1, Math.min(page, this.totalPages));
this.onChange(this.currentPage);
}
render(container) {
// 实现类似前面的renderPagination方法
}
}






