当前位置:首页 > JavaScript

js分页实现

2026-01-15 15:14:23JavaScript

分页的基本原理

分页的核心是通过计算当前页码和数据偏移量,从服务器或本地数据中截取对应范围的数据进行展示。通常需要以下参数:当前页码(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方法
  }
}

js分页实现

标签: 分页js
分享给朋友:

相关文章

vue实现页面分页

vue实现页面分页

Vue实现页面分页的方法 使用Element UI的分页组件 Element UI提供了现成的分页组件el-pagination,可以快速实现分页功能。需要先安装Element UI库。 <t…

js实现拖拽

js实现拖拽

实现拖拽的基本步骤 使用JavaScript实现拖拽功能需要监听鼠标事件,包括mousedown、mousemove和mouseup。以下是实现的基本逻辑: const draggableEleme…

js实现轮播图

js实现轮播图

轮播图实现方法 基础HTML结构 <div class="slider"> <div class="slides"> <img src="image1.jpg…

vue实现js休眠

vue实现js休眠

Vue 中实现 JavaScript 休眠 在 Vue 中实现 JavaScript 休眠通常需要使用异步方式,以避免阻塞主线程。以下是几种常见方法: 使用 setTimeout 和 Pro…

js实现vue路由

js实现vue路由

Vue路由基础实现 使用Vue Router实现前端路由需要先安装并配置路由库。Vue Router是Vue.js官方的路由管理器。 安装Vue Router: npm install vue-r…

分页用vue实现

分页用vue实现

分页用 Vue 实现 在 Vue 中实现分页功能通常需要结合数据管理和 UI 组件。以下是几种常见的方法: 使用 Vue 组件库的分页组件 许多 Vue UI 组件库(如 Element UI、Va…