使用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 函数更新当前页。
相关推荐
Freedom风间4 小时前
前端优秀编码技巧
前端·javascript·代码规范
萌萌哒草头将军4 小时前
🚀🚀🚀 Openapi:全栈开发神器,0代码写后端!
前端·javascript·next.js
萌萌哒草头将军4 小时前
🚀🚀🚀 Prisma 爱之初体验:一款非常棒的 ORM 工具库
前端·javascript·orm
拉不动的猪5 小时前
SDK与API简单对比
前端·javascript·面试
runnerdancer5 小时前
微信小程序蓝牙通信开发之分包传输通信协议开发
前端
BillKu5 小时前
Vue3后代组件多祖先通讯设计方案
开发语言·javascript·ecmascript
山海上的风5 小时前
Vue里面elementUi-aside 和el-main不垂直排列
前端·vue.js·elementui
电商api接口开发5 小时前
ASP.NET MVC 入门指南二
前端·c#·html·mvc
亭台烟雨中5 小时前
【前端记事】关于electron的入门使用
前端·javascript·electron