如何用JavaScript封装高效的前端分页库?分享我的思路与实践

67 min read

实现前端分页的基本流程如下:

1.获取数据:从服务器或本地获取所需的数据。

2.计算分页:根据每页显示的数据数量和数据总量计算出总页数。

3.渲染分页控件:按照指定的样式,将分页控件渲染到页面上。

4.绑定事件:对分页控件中的事件(例如点击页码、上一页、下一页等)进行绑定。

5.根据当前页码,获取对应的数据。

以下是一个伪代码实现前端分页的例子:

class Pagination {
  constructor(element, options) {
    this.element = element;
    this.currentPage = options.initialPage || 1;
    this.itemsPerPage = options.itemsPerPage || 10;
    this.totalItems = options.totalItems || 0;

    this.render();
    this.bindEvents();
  }

  render() {
    // 计算总页数
    const totalPages = Math.ceil(this.totalItems / this.itemsPerPage);

    // 渲染分页控件
    const pagination = document.createElement('ul');
    pagination.classList.add('pagination');

    // 添加上一页
    const prevPage = document.createElement('li');
    prevPage.innerHTML = '<span>&laquo;</span>';
    prevPage.dataset.page = this.currentPage - 1;
    if (this.currentPage === 1) prevPage.classList.add('disabled');
    pagination.appendChild(prevPage);

    // 添加页码
    for (let i = 1; i <= totalPages; i++) {
      const page = document.createElement('li');
      page.innerHTML = `<span>${i}</span>`;
      page.dataset.page = i;
      if (i === this.currentPage) page.classList.add('active');
      pagination.appendChild(page);
    }

    // 添加下一页
    const nextPage = document.createElement('li');
    nextPage.innerHTML = '<span>&raquo;</span>';
    nextPage.dataset.page = this.currentPage + 1;
    if (this.currentPage === totalPages) nextPage.classList.add('disabled');
    pagination.appendChild(nextPage);

    this.element.appendChild(pagination);
  }

  bindEvents() {
    this.element.addEventListener('click', event => {
      const pageItem = event.target.closest('li');
      if (!pageItem) return;

      const newPage = parseInt(pageItem.dataset.page);
      if (isNaN(newPage)) return;

      if (newPage === this.currentPage) return;
      if (newPage < 1 || newPage > Math.ceil(this.totalItems / this.itemsPerPage)) return;

      this.currentPage = newPage;
      this.render();

      // 触发回调函数
      if (this.onPageChange) {
        this.onPageChange(this.currentPage);
      }
    })
  }

  // 获取当前页的数据
  getCurrentPageData(data) {
    const start = (this.currentPage - 1) * this.itemsPerPage;
    const end = start + this.itemsPerPage;
    return data.slice(start, end);
  }

  // 更新分页总项数
  updateTotalItems(totalItems) {
    this.totalItems = totalItems;
    this.render();
  }
}

// 使用方式
const container = document.getElementById('pagination');
const pagination = new Pagination(container, {
  itemsPerPage: 10,
  totalItems: 100,
  initialPage: 1
});

pagination.onPageChange = (page) => {
  // 处理页面数据变化
  console.log(page);
}

以上是一个较为简单的前端分页库的基本实现,当然还有很多优化和扩展待完成,比如优化渲染方式、加入跳转页码输入框等等。