前言:
有些时候前端从后台拿到数据(数据量大,接口没有分页的情况下),需要前端实现分页(接口有分页的忽略),并根据页面的需求删除数据,在传给后台
关键字:
分页,数组的批量删除(参考:https://www.cnblogs.com/shun1015/p/12936362.html)
页面效果
下面是代码,每一步都有注释
1 <template> 2 <div class="home"> 3 <el-button type="info" size="small" plain @click="removeTabledata">删除</el-button> 4 <div class="table"> 5 <el-table 6 :data="showtabledata" 7 style=" 100%" 8 border 9 stripe 10 @selection-change="handleChange" 11 > 12 <el-table-column type="selection" width="55"></el-table-column> 13 <el-table-column prop="realName" label="姓名"></el-table-column> 14 <el-table-column prop="activityDate" label="日期"></el-table-column> 15 <el-table-column prop="agentId" label="Id"></el-table-column> 16 </el-table> 17 <el-pagination 18 style="text-align: center;" 19 background 20 @current-change="handleCurrentChange" 21 :current-page="person.page" 22 :page-size="person.size" 23 layout="total, prev, pager, next, jumper" 24 :total="total" 25 ></el-pagination> 26 </div> 27 </div> 28 </template> 29 30 <script> 31 import Data from "./data.json"; 32 export default { 33 name: "home", 34 data() { 35 return { 36 tableData: JSON.parse(JSON.stringify(Data)).data, //获取到全部数据 37 showtabledata: [], // 分页展示的数据 38 person: { page: 1, size: 10 }, 39 removeList: [], // 选中需要删除的数据 40 Page: 1, // 记录当前的页码 41 }; 42 }, 43 computed: { 44 // 总数 45 total() { 46 return this.tableData.length; 47 }, 48 }, 49 created() { 50 console.log(this.tableData); 51 this.ShowData(this.Page); // 页面初始化,显示第一页的数据 52 }, 53 methods: { 54 // 封装 分页方法 55 ShowData(e) { 56 this.showtabledata = this.tableData.slice(e * 10 - 10, e * 10); 57 }, 58 // 分页效果 59 handleCurrentChange(val) { // 每次页码改变 60 this.ShowData(val); 61 this.Page = val; 62 }, 63 // table的checkbox事件,选中删除的数据 64 handleChange(val) { 65 console.log(val); 66 this.removeList = val; 67 }, 68 // 删除 69 removeTabledata() { 70 if (this.removeList.length === 0) { 71 return this.$message.warning("请选择要删除的人员"); 72 } 73 this.tableData = this.remove(this.tableData, this.removeList); // 总数和需要删除的数据 74 console.log(this.tableData); // 删除选中之后的总数 75 if (this.tableData.length >= 10 && this.tableData.length % 10 === 0) { // (第一页除外)每次删除可能会把当前这一页的数据删除完,这时候需要请求上一页的数据 76 this.ShowData(this.Page - 1); 77 this.Page = this.Page - 1; // 记得一定要将页码设置回去 78 } else { 79 this.ShowData(this.Page); 80 } 81 this.$message.success("删除成功") 82 }, 83 // 删除封装方法 84 remove(arr1, arr2) { 85 for (let i = 0; i < arr2.length; i++) { 86 for (let j = 0; j < arr1.length; j++) { 87 if (arr2[i].agentId === arr1[j].agentId) { 88 let indexs = arr1.indexOf(arr1[j]); 89 arr1.splice(indexs, 1); 90 } 91 } 92 } 93 return arr1; 94 }, 95 }, 96 }; 97 </script>