当前位置:首页 > JavaScript

js分页实现前端实现

2026-02-01 22:30:53JavaScript

分页前端实现方法

基于数组的分页

通过数组的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;
}

无限滚动分页

js分页实现前端实现

适用于移动端或需要流畅浏览体验的场景,通过监听滚动事件动态加载数据:

window.addEventListener('scroll', () => {
  if (window.innerHeight + window.scrollY >= document.body.offsetHeight - 500) {
    if (!isLoading) {
      loadMoreData();
    }
  }
});

function loadMoreData() {
  isLoading = true;
  // 获取下一页数据的逻辑
}

与API配合的分页

当前端需要从后端获取分页数据时,通常需要传递页码和每页大小参数:

js分页实现前端实现

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)` }
  }));
}

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

相关文章

js实现验证码

js实现验证码

实现验证码的JavaScript方法 生成随机验证码 使用Math.random()生成随机字符串,结合数字和字母: function generateCaptcha() { const cha…

js 实现继承

js 实现继承

原型链继承 通过让子类的原型对象指向父类的实例来实现继承。子类实例可以访问父类原型上的属性和方法。 function Parent() { this.name = 'parent'; } Par…

js实现拷贝

js实现拷贝

实现文本拷贝 使用 document.execCommand 方法(已废弃但兼容性较好): function copyText(text) { const textarea = document…

js分组实现

js分组实现

分组实现方法 在JavaScript中,可以通过多种方式实现数组或对象的分组操作。以下是几种常见的方法: 使用Array.prototype.reduce() 通过reduce方法可以轻松实现数组分…

js实现授权

js实现授权

授权流程设计 授权流程通常涉及前端与后端的交互,常见方案包括OAuth2.0、JWT等。以JWT为例的典型流程: 用户提交凭证(如用户名密码)到认证服务 服务端验证通过后生成包含用户信息的J…

js 实现滚动

js 实现滚动

实现滚动的方法 使用 window.scrollTo() window.scrollTo() 方法可以滚动到文档中的特定位置。可以指定 x 和 y 坐标,或者使用平滑滚动的选项。 // 滚动到指定位…