当前位置:首页 > JavaScript

js实现分页功能代码

2026-01-13 14:21:24JavaScript

分页功能实现方法

客户端分页(前端处理数据)

适用于数据量较小且已全部加载到前端的情况。

// 示例数据
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分页更适合处理大量数据。

js实现分页功能代码

标签: 分页代码
分享给朋友:

相关文章

vue搜索过后实现分页

vue搜索过后实现分页

Vue 实现搜索后分页功能 数据绑定与搜索逻辑 在 Vue 组件中定义必要的数据属性: data() { return { searchQuery: '', currentPa…

分页实现vue

分页实现vue

分页实现(Vue) 在Vue中实现分页功能通常需要结合前端分页逻辑和后端API支持。以下是两种常见的实现方式: 前端分页实现 适用于数据量较小的情况,直接在客户端完成分页逻辑。 <tem…

vue分页实现

vue分页实现

实现Vue分页的几种方法 使用Element UI的分页组件 安装Element UI库后,可以直接使用其分页组件。以下是一个基本示例: <template> <div>…

vue怎么实现文本代码实现

vue怎么实现文本代码实现

Vue 实现文本代码展示的方法 在 Vue 中展示代码块或格式化文本,可以通过多种方式实现。以下是几种常见方法: 使用 <pre> 和 <code> 标签 最简单的原生 HT…

vue实现分页条数

vue实现分页条数

实现分页条数的方法 在Vue中实现分页条数功能,通常需要结合分页组件和数据请求逻辑。以下是几种常见的实现方式: 使用Element UI的分页组件 Element UI提供了现成的分页组件,可…

vue实现页面分页

vue实现页面分页

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