js分页实现前端实现
分页前端实现方法
基于数组的分页
通过数组的slice方法实现数据分页,适用于数据量较小的情况:
const data = [/* 数据数组 */];
const pageSize = 10; // 每页显示数量
const currentPage = 1; // 当前页码
const paginatedData = data.slice(
(currentPage - 1) * pageSize,
currentPage * pageSize
);
动态渲染分页器
创建可交互的分页控件,通常包含页码按钮和导航功能:
function renderPagination(totalPages, currentPage) {
let paginationHTML = '<div class="pagination">';
// 上一页按钮
paginationHTML += `<button ${currentPage === 1 ? 'disabled' : ''}
onclick="changePage(${currentPage - 1})">上一页</button>`;
// 页码按钮
for (let i = 1; i <= totalPages; i++) {
paginationHTML += `<button ${i === currentPage ? 'class="active"' : ''}
onclick="changePage(${i})">${i}</button>`;
}
// 下一页按钮
paginationHTML += `<button ${currentPage === totalPages ? 'disabled' : ''}
onclick="changePage(${currentPage + 1})">下一页</button>`;
paginationHTML += '</div>';
document.getElementById('pagination').innerHTML = paginationHTML;
}
无限滚动分页
适用于移动端或需要流畅浏览体验的场景,通过监听滚动事件动态加载数据:
window.addEventListener('scroll', () => {
if (window.innerHeight + window.scrollY >= document.body.offsetHeight - 500) {
if (!isLoading) {
loadMoreData();
}
}
});
function loadMoreData() {
isLoading = true;
// 获取下一页数据的逻辑
}
与API配合的分页
当前端需要从后端获取分页数据时,通常需要传递页码和每页大小参数:
async function fetchPaginatedData(page, size) {
const response = await fetch(`/api/data?page=${page}&size=${size}`);
const result = await response.json();
return {
data: result.items,
total: result.totalCount
};
}
分页组件封装
可复用的分页组件实现示例(Vue版本):
Vue.component('pagination', {
props: ['total', 'current', 'pageSize'],
template: `
<div class="pagination">
<button @click="prev" :disabled="current === 1">上一页</button>
<span v-for="page in pages" :key="page">
<button @click="goTo(page)" :class="{active: page === current}">
{{ page }}
</button>
</span>
<button @click="next" :disabled="current === pageCount">下一页</button>
</div>
`,
computed: {
pageCount() {
return Math.ceil(this.total / this.pageSize);
},
pages() {
// 生成可见页码数组的逻辑
}
},
methods: {
goTo(page) {
this.$emit('page-changed', page);
},
prev() {
this.goTo(this.current - 1);
},
next() {
this.goTo(this.current + 1);
}
}
});
性能优化技巧
大数据量分页时可采用虚拟滚动技术,只渲染可视区域内的数据:
function virtualScroll(items, containerHeight, itemHeight) {
const scrollTop = container.scrollTop;
const startIndex = Math.floor(scrollTop / itemHeight);
const endIndex = Math.min(
startIndex + Math.ceil(containerHeight / itemHeight),
items.length
);
return items.slice(startIndex, endIndex).map((item, index) => ({
...item,
style: { transform: `translateY(${(startIndex + index) * itemHeight}px)` }
}));
}






