ElementUI Table組件,如何在多頁數據下勾選多行

ElementUI Table組件,選擇多行數據時使用 Checkbox。以下圖:bash

可是業務中,表格數據每每不僅一頁。多頁數據狀況下,表格勾選某些行,就會遇到返回上一頁,勾選消失的狀況。這種狀況,須要一些技巧和處理。具體代碼以下:ui

<template>
  <div class="demo-example">
    <el-table
      ref="table"
      v-loading="loading"
      :data="list"
      height="650"
      border
      @select="onSelect"
      @select-all="onSelectAll"
      @selection-change="onSelectionChange"
    >
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="u_createTime" label="註冊時間"></el-table-column>
      <el-table-column prop="u_id" label="用戶ID"></el-table-column>
      <el-table-column prop="u_nickname" label="用戶名稱"></el-table-column>
      <el-table-column prop="u_phone" label="用戶帳戶"></el-table-column>
      <el-table-column prop="u_gender" label="性別"></el-table-column>
      <el-table-column label="角色">
        <template slot-scope="scope">
          <span>{{scope.row.u_role === 1 ? '團隊長' : '保險人'}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="u_companyNum" label="所屬企業數量"></el-table-column>
      <el-table-column prop="ha_addPeople" label="所屬羣組">
        <template slot-scope="scope">
          <el-button @click="onChakan(scope.row)" type="text" style="color:#67c23a" size="small">查看</el-button>
        </template>
      </el-table-column>
      <el-table-column prop="u_lastLoginTime" label="最近登陸時間"></el-table-column>
    </el-table>

    <div class="block pag" v-if="total">
      <el-pagination
        @current-change="onChangePage"
        :current-page="currentPage"
        :page-size="10"
        layout="total, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>
  </div>
</template>
<script>

export default {
  data() {
    return {
      selections: {}, // 保存已選擇過的row
      list: [],
      total: 0,
      curPage: 1,
    };
  },

  //方法事件
  methods: {
    // 勾選時候,記錄[{u_id: row}, ...]
    onSelect(selection, row) {
      if (this.selections[row.u_id]) {
        delete this.selections[row.u_id];
      } else {
        this.selections[row.u_id] = row;
      }
    },

    // 全選狀況
    onSelectAll(selection) {
        // 全選
        if (selection.length) {
            selection.forEach(row => {
                this.selections[row.u_id] = row;
            })
        } else {
            // 取消全選
            this.list.forEach(row => {
                delete this.selections[row.u_id];
            })
        }

    },

    // 對已選擇過的row勾選,返回到上一頁時候
    checkRows() {
      const keys = Object.keys(this.selections);
      const rows = this.list.filter(row => {
        return keys.includes(String(row.u_id));
      });

      rows.map(row => {
        this.$refs.table.toggleRowSelection(row);
      });
    },

    // 省略...

    // 獲取數據列表
    getData() {
      // ...
    },

  },

  created() {
    this.getData();
  }
};
</script>
複製代碼

如今分頁切換,勾選依然會顯示,對應每頁勾選過的行數據。須要提交的勾選數據,也都在this.selections對象中。this

相關文章
相關標籤/搜索