如何用js实现分页
分页实现的基本逻辑
分页的核心是将大量数据分割成多个页面展示。通常需要计算总页数、当前页数据范围,并处理用户翻页操作。
前端分页实现
纯前端分页适用于数据量较小的情况,所有数据一次性加载后由前端分割:

// 示例数据
const allData = [...]; // 完整数据集
const pageSize = 10; // 每页条数
function paginate(data, currentPage, pageSize) {
const startIndex = (currentPage - 1) * pageSize;
return data.slice(startIndex, startIndex + pageSize);
}
// 获取第2页数据
const page2Data = paginate(allData, 2, pageSize);
后端分页实现
实际项目更常用后端分页,通过API传递分页参数:

async function fetchPaginatedData(page, size) {
const response = await fetch(`/api/data?page=${page}&size=${size}`);
return response.json();
}
// 使用示例
fetchPaginatedData(1, 10).then(data => {
console.log(data.items); // 当前页数据
console.log(data.total); // 总数据量
});
分页组件实现
完整的分页UI组件通常包含页码导航:
class Pagination {
constructor(totalItems, itemsPerPage) {
this.totalItems = totalItems;
this.itemsPerPage = itemsPerPage;
this.currentPage = 1;
}
get totalPages() {
return Math.ceil(this.totalItems / this.itemsPerPage);
}
render() {
const container = document.createElement('div');
container.className = 'pagination';
for (let i = 1; i <= this.totalPages; i++) {
const pageBtn = document.createElement('button');
pageBtn.textContent = i;
pageBtn.disabled = i === this.currentPage;
pageBtn.addEventListener('click', () => this.goToPage(i));
container.appendChild(pageBtn);
}
return container;
}
goToPage(page) {
this.currentPage = page;
// 触发数据更新
}
}
分页优化技巧
- 添加省略号处理大量页码
- 实现页码缓存避免重复请求
- 支持动态修改每页显示数量
- 添加加载状态提示
现代框架实现示例
在React中可以使用自定义hook:
function usePagination(data, itemsPerPage) {
const [currentPage, setCurrentPage] = useState(1);
const maxPage = Math.ceil(data.length / itemsPerPage);
function currentData() {
const begin = (currentPage - 1) * itemsPerPage;
const end = begin + itemsPerPage;
return data.slice(begin, end);
}
return { currentData, currentPage, maxPage, setCurrentPage };
}
分页实现应根据具体项目需求选择合适方案,考虑数据量、性能要求和用户体验等因素。






