转载:https://www.cnblogs.com/hcxy/p/9482762.html <template> <div class="table-demo"> <el-table ref="multipleTable" :data="rowData" tooltip-effect="dark" style="width: 100%" @selection-change="changeFun" @select="selectMemoryFn" @select-all="selectAll" > <el-table-column type="selection" width="55"></el-table-column> <el-table-column label="日期" width="120"> <template slot-scope="{ row }">{{ row.date }}</template> </el-table-column> <el-table-column prop="name" label="姓名" width="120"></el-table-column> <el-table-column prop="address" label="地址" show-overflow-tooltip></el-table-column> </el-table> <el-pagination layout="prev, pager, next" :total="total" :current-page="currentPage" @current-change="handleCurrentChange" > </el-pagination> </div> </template>
<script> import { getAddressList } from '../api/getData' export default { data () { return { currentPage: 1, pageSize: 10, total: 12, // 随便定义一个形成分页的数字 rowData: [], multipleSelection: [], // 选中的数据二维数组 ids: [] // 选中的数据id数组 } }, methods: { changeFun (val) { // 保存已选数据id到数组,供后续操作(与分页记忆无关) this.$nextTick(() => { let ids = [] this.multipleSelection.forEach(L => L.forEach(M => ids.push(M.id))) this.ids = ids }) }, selectAll (selection) { // 全选切换方法 if (selection.length) { // 全选 this.multipleSelection[this.currentPage - 1] = selection } else { // 全不选 this.multipleSelection[this.currentPage - 1] = [] } }, selectMemoryFn (val, row) { // 设置分页记忆二位数组方法 // 注意:val 传过来默认为数组类型 ,row 为 Object(当前选择数据对象) let currentArr = this.multipleSelection[this.currentPage - 1] // 当前分页对应数组 if (!currentArr) { this.multipleSelection[this.currentPage - 1] = val // 不存在这个二维数组,则创建这个二位数组 } else { // 存在 if (val.includes(row)) { // 选中 this.multipleSelection[this.currentPage - 1] = val } else { // 取消 delete currentArr[currentArr.indexOf(row)] } } }, selectMemoriedDataFn () { // 分页记忆自动选中方法 let currentArr = this.multipleSelection[this.currentPage - 1] // 当前分页对应被选中数据 if (currentArr && currentArr.length) { // 存在则继续执行 let tempRowsIDs = this.rowData.map(L => L.id) // 当前分页被选中数据的id集合 currentArr.forEach((item, index) => { // 遍历当前分页被选中数据 if (tempRowsIDs.includes(item.id)) { // id匹配上,则选中 this.$refs.multipleTable.toggleRowSelection(this.rowData[tempRowsIDs.indexOf(item.id)]) } }) } }, handleCurrentChange (val) { // 分页切换,重新加载数据 this.currentPage = val this.init() }, async init () { // 初始化获取数据 let res = await getAddressList({ page: this.currentPage }) this.rowData = res.rows } }, watch: { rowData (oldVal, newVal) { // 监听数据变化,然后执行分页记忆自动选中回调 this.$nextTick(() => { this.selectMemoriedDataFn() }) } }, created () { this.init() } } </script>