实现思路
通过 setTimeout() 延迟1s 给数据赋值来模拟后端接口异步获取数据
最终效果
完整代码
<template> <div class="mainBox"> <el-table v-loading="loading" :data="tableData"> <el-table-column prop="ID" label="编号" align="center"> </el-table-column> <el-table-column prop="name" label="姓名" align="center"> </el-table-column> <el-table-column prop="age" label="年龄" align="center"> </el-table-column> </el-table> <el-row type="flex" class="pageBanner" justify="center"> <el-pagination background :total="total" :page-size="pageSize" @size-change="pageSizeChange" @current-change="currentPageChange" :current-page="currentPage" :page-sizes="pageSizes" layout="total, sizes, prev, pager, next, jumper" > </el-pagination> </el-row> </div> </template> <script> export default { data() { return { loading: false, total: 0, pageSize: 3, pageSizes: [1, 2, 3, 5, 10], currentPage: 1, tableData: [], }; }, mounted() { // 页面初始化时,首次加载数据 this.getData(this.currentPage, this.pageSize); }, methods: { // 模拟访问接口获取数据 getData(page, pageSize) { this.loading = true; setTimeout( () => { let data = [ { ID: 1, name: "王小虎", age: 10, }, { ID: 2, name: "张三", age: 20, }, { ID: 3, name: "李四", age: 30, }, { ID: 4, name: "何香", age: 18, }, { ID: 5, name: "刘刀", age: 27, }, { ID: 6, name: "关胜", age: 33, }, { ID: 7, name: "齐巧", age: 55, }, { ID: 8, name: "卢一方", age: 45, }, { ID: 9, name: "王兴海", age: 66, }, { ID: 10, name: "全德", age: 100, }, ]; this.total = data.length; let startIndex = pageSize * (page - 1); let endIndex = pageSize * page; this.tableData = data.slice(startIndex, endIndex); this.loading = false; }, // 延迟1s后执行,模拟异步获取数据 1000 ); }, // 切换页码--翻页 currentPageChange(newPage) { this.currentPage = newPage; this.getData(this.currentPage, this.pageSize); }, // 切换每页显示条数 pageSizeChange(newPageSize) { this.pageSize = newPageSize; this.getData(this.currentPage, this.pageSize); }, }, }; </script> <style scoped> .mainBox { margin: 30px; } .pageBanner { margin: 10px; } </style>