js实现分页功能代码
分页功能实现方法
客户端分页(前端处理数据)
适用于数据量较小且已全部加载到前端的情况。
// 示例数据
const data = Array.from({length: 100}, (_, i) => ({id: i+1, content: `Item ${i+1}`}));
function paginate(items, page = 1, perPage = 10) {
const offset = (page - 1) * perPage;
const paginatedItems = items.slice(offset, offset + perPage);
const totalPages = Math.ceil(items.length / perPage);
return {
currentPage: page,
perPage,
total: items.length,
totalPages,
data: paginatedItems
};
}
// 使用示例
const result = paginate(data, 2); // 获取第二页数据
console.log(result);
服务器端分页(API请求)
适用于大数据量场景,需要与后端API配合。
async function fetchPaginatedData(page = 1, pageSize = 10) {
try {
const response = await fetch(`/api/data?page=${page}&size=${pageSize}`);
const result = await response.json();
// 典型API返回结构示例
// {
// data: [],
// currentPage: 1,
// totalItems: 100,
// totalPages: 10
// }
return result;
} catch (error) {
console.error('Fetch error:', error);
return null;
}
}
// 使用示例
fetchPaginatedData(3, 15).then(data => {
console.log('Page 3 data:', data);
});
分页UI组件实现
结合DOM操作的分页控件示例。
function createPagination(totalPages, currentPage, container) {
container.innerHTML = '';
// 上一页按钮
if (currentPage > 1) {
const prevBtn = document.createElement('button');
prevBtn.textContent = 'Previous';
prevBtn.addEventListener('click', () => updatePage(currentPage - 1));
container.appendChild(prevBtn);
}
// 页码按钮
for (let i = 1; i <= totalPages; i++) {
const pageBtn = document.createElement('button');
pageBtn.textContent = i;
if (i === currentPage) {
pageBtn.classList.add('active');
}
pageBtn.addEventListener('click', () => updatePage(i));
container.appendChild(pageBtn);
}
// 下一页按钮
if (currentPage < totalPages) {
const nextBtn = document.createElement('button');
nextBtn.textContent = 'Next';
nextBtn.addEventListener('click', () => updatePage(currentPage + 1));
container.appendChild(nextBtn);
}
}
// 使用示例
const paginationContainer = document.getElementById('pagination');
createPagination(10, 1, paginationContainer);
React分页组件示例
适用于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+1}
className={currentPage === i+1 ? 'active' : ''}
onClick={() => onPageChange(i+1)}
>
{i+1}
</button>
))}
<button
disabled={currentPage === totalPages}
onClick={() => onPageChange(currentPage + 1)}
>
Next
</button>
</div>
);
}
Vue分页组件示例
适用于Vue框架的实现。
<template>
<div class="pagination">
<button
:disabled="currentPage === 1"
@click="changePage(currentPage - 1)"
>
Previous
</button>
<button
v-for="page in totalPages"
:key="page"
:class="{ active: currentPage === page }"
@click="changePage(page)"
>
{{ page }}
</button>
<button
:disabled="currentPage === totalPages"
@click="changePage(currentPage + 1)"
>
Next
</button>
</div>
</template>
<script>
export default {
props: {
currentPage: Number,
totalPages: Number
},
methods: {
changePage(page) {
this.$emit('page-changed', page);
}
}
};
</script>
这些实现方法涵盖了从纯JavaScript到主流框架的分页功能,可根据具体项目需求选择适合的方案。前端分页适合小数据集,而API分页更适合处理大量数据。







