Element-ui中el-table分页调接口,跨分页后数据如何进行回显

110 阅读1分钟

如图:

Image_20231020091407.png

<template>
  <el-card>
    <el-table
      ref="multipleTable"
      :data="tableData.content"
      style="width: 100%"
      @select="onSelect"
      @select-all="onAllSelect"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="id" label="id" />
      <el-table-column prop="name" label="名称" />
    </el-table>
    <el-pagination
      layout="prev, pager, next"
      :total="tableData.totalCount"
      :page-size="pagination.pageSize"
      @current-change="handleCurrentChange"
    >
    </el-pagination>
  </el-card>
</template>

<script>
export default {
  data() {
    return {
      tableData: {
        content: [],
        totalCount: null
      },
      pagination: {
        pageSize: 3,
        pageNumber: 1
      },
      selectedData: []
    };
  },
  mounted() {
    this.getTableData();
  },
  methods: {
    // Mock数据
    callApi() {
      return {
        totalCount: 9,
        1: [
          { id: 1, name: '11111' },
          { id: 2, name: '2222' },
          { id: 3, name: '3333' }
        ],
        2: [
          { id: 4, name: '4444' },
          { id: 5, name: '5555' },
          { id: 6, name: '66666' }
        ],
        3: [
          { id: 7, name: '77777' },
          { id: 8, name: '88888' },
          { id: 9, name: '99999' }
        ]
      };
    },
    // 获取表格数据
    getTableData() {
      const resData = this.callApi();
      this.tableData.totalCount = resData?.totalCount;
      this.tableData.content = resData?.[this.pagination.pageNumber];
      this.$nextTick(() => {
        this.toggleSelection();
      });
    },
    handleCurrentChange(value) {
      this.pagination.pageNumber = value;
      this.getTableData();
    },
    // 勾选数据行(单行选择)
    onSelect(selection, row) {
      if (selection.includes(row)) {
        // 加
        return selection.forEach(item => {
          if (!this.selectedData.includes(item)) {
            this.selectedData.push(item);
          }
        });
      }
      // 减
      this.selectedData = this.selectedData.filter(item => item.id !== row.id);
    },
    // 全选
    onAllSelect(selection) {
      // 加
      if (selection?.length > 0) {
        return selection.forEach(item => {
          if (!this.selectedData.includes(item)) {
            this.selectedData.push(item);
          }
        });
      }
      // 减
      this.selectedData = this.selectedData.filter(item => {
        const currentTableIds = this.tableData?.content?.map(map => map.id);
        return !currentTableIds.includes(item.id);
      });
    },
    // 表格某行数据选中状态(回显)
    toggleSelection() {
      this.tableData?.content.forEach(select => {
        if (this.selectedData.some(item => item.id === select.id)) {
          this.$refs.multipleTable.toggleRowSelection(select);
        }
      });
    }
  }
};
</script>