在 element-ui 的表格组件中,实现进行分页操作保留上一页

在 element-ui 的表格组件中,当进行分页加载数据时,如果需要保留前一页选择的数据,通常可以使用数组来保存所有已选择的数据,而不是只保存当前页的选中数据。

下面是一个参考示例,其中使用 selection 数组来保存选中数据,每次选择后都将选中的数据放到 selection 中,取消选择时则将对应的数据从 selection 中移除。当切换分页时,可以通过 selection 数组的内容来设置当前页的选中数据。

<template>
  <div>
    <el-table
      :data="tableData"
      :row-key="row => row.id"
      @selection-change="handleSelectionChange"
    >
      <!-- 表头等省略 -->
      <el-table-column
        type="selection"
        :selectable="row => row.enabled"
      ></el-table-column>
    </el-table>
    <el-pagination
      :total="total"
      :current-page="currentPage"
      :page-size="pageSize"
      @current-change="handleCurrentChange"
    ></el-pagination>
  </div>
</template>

<script>
export default {
  data() {
    return {
      tableData: [],
      selection: [],
      total: 100,
      currentPage: 1,
      pageSize: 10,
    }
  },
  methods: {
    // 触发表格选择事件时,将选中的数据添加到 selection 数组中
    handleSelectionChange(selection) {
      this.selection.push(...selection)
    },
    // 触发分页事件时,根据 selection 数组设置当前页的选中数据
    handleCurrentChange(currentPage) {
      this.currentPage = currentPage

      // 根据选中数据设置当前页的选中状态
      this.tableData.forEach(row => {
        this.$refs.table.toggleRowSelection(row, this.selection.includes(row))
      })
    },
    // 加载当前页的数据,如果该页中有已选中的数据,则设置其为选中状态
    async loadData() {
      // 省略获取数据的异步操作
      const data = await fetchData(this.currentPage, this.pageSize)

      // 将数据设置为表格的数据源
      this.tableData = data.data

      // 根据选中数据设置当前页的选中状态
      this.tableData.forEach(row => {
        this.$refs.table.toggleRowSelection(row, this.selection.includes(row))
      })
    }
  },
  mounted() {
    // 加载第一页数据
    this.loadData()
  }
}
</script>

在上面的代码中,我们通过 selection 数组来保存选中数据,每当选择或取消选择某行时,将其加入或从 selection 移除,然后在切换分页时,根据 selection 数组来设置当前页的选中状态。再加载新数据时,如果选中的数据已经包含在新数据中,也会自动选中它们,因为在加载数据时 selection 数组的内容是不会丢失的。

需要注意的是,在这种情况下,因为多页数据的选中数据需要在各个页之间共享,所以不能使用内部状态 tableData 中的 selected 属性,这样的话只能保留当前页的选中数据。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值