js 分页实现
分页实现的基本原理
分页的核心是将大量数据分割成多个小块,每次只加载或显示其中一部分。通常需要计算总页数、当前页码、每页数据量等参数,结合前端渲染或后端接口实现。
前端分页实现
适用于数据量较小且已全部加载到前端的情况,通过数组切片实现分页。
// 示例数据
const allData = [...Array(100).keys()].map(i => ({ id: i, name: `Item ${i}` }));
function paginateFrontend(data, currentPage, itemsPerPage) {
const startIndex = (currentPage - 1) * itemsPerPage;
return data.slice(startIndex, startIndex + itemsPerPage);
}
// 使用示例
const currentPage = 2;
const itemsPerPage = 10;
const pageData = paginateFrontend(allData, currentPage, itemsPerPage);
后端分页实现
通过API请求实现,常用limit和offset参数(或page和size)。
async function fetchPaginatedData(page, size) {
const response = await fetch(`/api/items?page=${page}&size=${size}`);
return response.json();
}
// 使用示例
fetchPaginatedData(1, 10).then(data => {
console.log(data.items, data.totalPages);
});
分页组件示例
常见UI分页组件实现逻辑(以React为例):
function Pagination({ currentPage, totalPages, onPageChange }) {
return (
<div className="pagination">
<button
disabled={currentPage === 1}
onClick={() => onPageChange(currentPage - 1)}
>Previous</button>
{Array.from({ length: totalPages }, (_, i) => (
<button
key={i}
className={currentPage === i + 1 ? 'active' : ''}
onClick={() => onPageChange(i + 1)}
>{i + 1}</button>
))}
<button
disabled={currentPage === totalPages}
onClick={() => onPageChange(currentPage + 1)}
>Next</button>
</div>
);
}
分页参数计算
计算分页相关参数的通用方法:
function calculatePagination(totalItems, currentPage, itemsPerPage) {
const totalPages = Math.ceil(totalItems / itemsPerPage);
currentPage = Math.max(1, Math.min(currentPage, totalPages));
const startIndex = (currentPage - 1) * itemsPerPage;
return {
currentPage,
totalPages,
startIndex,
endIndex: Math.min(startIndex + itemsPerPage - 1, totalItems - 1)
};
}
分页样式优化
CSS样式建议(配合上述组件):
.pagination {
display: flex;
gap: 5px;
}
.pagination button {
padding: 5px 10px;
border: 1px solid #ddd;
background: white;
}
.pagination button.active {
background: #007bff;
color: white;
}
.pagination button:disabled {
opacity: 0.5;
}
性能优化建议
大数据量分页时推荐使用无限滚动(Intersection Observer实现)或后端游标分页(cursor-based pagination),避免传统分页的性能问题。对于SQL数据库,推荐使用LIMIT offset, count语法时配合索引优化。







