需求:后端把所有数据都返给前端,前端进行分页渲染。
实现思路:先把数据存储到一个大数组中,然后调用方法进行切割。主要使用数组的slice方法
所有代码:
html
<template><div style="padding: 20px"><el-table :data="tableData"><el-table-column type="selection" width="55" /><el-table-column prop="username" label="用户名" show-overflow-tooltip /><el-table-column prop="firstName" label="姓名" show-overflow-tooltip /><el-table-column prop="email" label="邮箱" show-overflow-tooltip /></el-table><!-- 分页器 --><div class="pagination"><el-paginationv-model:current-page="pagination.pageNum"v-model:page-size="pagination.pageSize":page-sizes="[10, 20, 50, 100]"layout="total, prev, pager, next,sizes, jumper":total="pagination.total"@size-change="handleSizeChange"@current-change="handleCurrentChange"/></div></div>
</template>
js
<script setup lang="ts">
import { ref, reactive } from "vue";let tableData = ref<any>([]); // 表格数据
let allList = reactive<any>([]);
//分页器
const pagination = reactive<any>({pageNum: 1,pageSize: 10,total: 0,
});// 前端分页-切割数据
const paging = () => {// 起始位置 = (当前页 - 1) x 每页的大小const start = (pagination.pageNum - 1) * pagination.pageSize;// 结束位置 = 当前页 x 每页的大小const end = pagination.pageNum * pagination.pageSize;tableData.value = allList.slice(start, end);
};// 获取列表数据
const getList = async () => {// 接口请求allList = [{id:1, username: "admin1", firstName: "管理员", email: "123456@163.com" },{id:2, username: "admin2", firstName: "管理员", email: "123456@163.com" },{id:3, username: "admin3", firstName: "管理员", email: "123456@163.com" },{id:4, username: "admin4", firstName: "管理员", email: "123456@163.com" },{id:5, username: "admin5", firstName: "管理员", email: "123456@163.com" },{id:6, username: "admin6", firstName: "管理员", email: "123456@163.com" },{id:7, username: "admin7", firstName: "管理员", email: "123456@163.com" },{id:8, username: "admin8", firstName: "管理员", email: "123456@163.com" },{id:9, username: "admin9", firstName: "管理员", email: "123456@163.com" },{id:10, username: "admin10", firstName: "管理员", email: "123456@163.com" },{id:11, username: "admin11", firstName: "管理员", email: "123456@163.com" },{id:12, username: "admin12", firstName: "管理员", email: "123456@163.com" },{id:13, username: "admin13", firstName: "管理员", email: "123456@163.com" },{id:14, username: "admin14", firstName: "管理员", email: "123456@163.com" },{id:15, username: "admin15", firstName: "管理员", email: "123456@163.com" },{id:16, username: "admin16", firstName: "管理员", email: "123456@163.com" },{id:17, username: "admin17", firstName: "管理员", email: "123456@163.com" },{id:18, username: "admin18", firstName: "管理员", email: "123456@163.com" },];pagination.total = allList.length;paging();
};
getList();// 分页事件
const handleSizeChange = (val: number) => {pagination.page = 1;pagination.limit = val;getList();
};
const handleCurrentChange = (val: number) => {pagination.page = val;getList();
};
</script>