使用elementplus中的分页器,后端一次性返100条数据,前端自己做分页处理,vue3写法

安装依赖

确保你已经安装了 Vue 3 和 Element Plus:

javascript 复制代码
npm install vue@next element-plus

组件

javascript 复制代码
<template>
  <div>
    <el-table :data="currentPageData" style="width: 100%">
      <el-table-column prop="name" label="姓名" />
      <el-table-column prop="age" label="年龄" />
      <el-table-column prop="email" label="邮箱" />
    </el-table>

    <el-pagination
      v-model:current-page="currentPage"
      :page-size="pageSize"
      :total="totalData"
      @current-change="handlePageChange"
      layout="total, prev, pager, next, jumper"
    />
  </div>
</template>

<script>
import { ref, computed } from 'vue';

export default {
  setup() {
    const data = ref([]); // 存放从后端获取的数据
    const currentPage = ref(1);
    const pageSize = ref(10); // 每页显示的条目数

    // 假设这里是从后端获取的数据
    const totalData = 100; // 总数据条数
    const fetchData = async () => {
      // 模拟异步请求
      const response = await new Promise((resolve) =>
        setTimeout(() => {
          // 生成模拟数据
          const data = Array.from({ length: totalData }, (_, index) => ({
            name: `姓名 ${index + 1}`,
            age: Math.floor(Math.random() * 40) + 20,
            email: `example${index + 1}@domain.com`,
          }));
          resolve(data);
        }, 1000)
      );
      data.value = response;
    };

    const currentPageData = computed(() => {
      const start = (currentPage.value - 1) * pageSize.value;
      const end = start + pageSize.value;
      return data.value.slice(start, end);
    });

    const handlePageChange = (newPage) => {
      currentPage.value = newPage;
    };

    // 在组件挂载时获取数据
    fetchData();

    return {
      data,
      currentPage,
      pageSize,
      totalData,
      currentPageData,
      handlePageChange,
    };
  },
};
</script>

<style>
/* 添加一些样式 */
</style>

说明

  • 数据获取:fetchData 函数模拟了一个异步请求,获取 100 条数据。
  • 分页逻辑:通过 computed 计算属性 currentPageData,根据当前页码和每页大小计算出当前显示的数据。
  • Element Plus 分页器:使用 el-pagination 组件实现分页功能,通过 v-model:current-page 绑定当前页,并在页码变化时调用 handlePageChange 函数更新当前页。
相关推荐
红尘散仙4 小时前
谁说终端只能敲键盘?我用 Rust 给小说阅读器加上了鼠标
前端·后端·rust
Penge6664 小时前
《Go 后端开发者学 React:组件通信与插槽》
javascript
陈随易5 小时前
C++26 草案被否,二十八年来头一回
前端·后端·程序员
ZhengEnCi6 小时前
Agent 工具怎么折叠海量输出才「爽」:Trae、Claude Code 的渐进式披露设计原理
前端·agent
Penge6666 小时前
《Go 后端开发者学 React:useState》
javascript
Penge6666 小时前
《Go 后端开发者学 React:数据渲染》
javascript
IT_陈寒9 小时前
Redis内存暴涨,没想到是AOF重写捣的鬼
前端·人工智能·后端
ikoala9 小时前
让 Codex 自己查账:一个省 token 的小技巧
前端·后端·ai编程
ikoala9 小时前
AI 写页面像说明书,修 Bug 像贴膏药?把这两句话写进 AGENTS.md
前端·javascript·ai编程
Penge6669 小时前
《Go 后端开发者学 TypeScript:ES Module了解》
javascript