1. 程式人生 > 實用技巧 >element-ui 樹形表格多選

element-ui 樹形表格多選

如題element-ui 2.13.2版本支援樹形結構tabel,多層級摺疊顯示

但是沒有多選 + 樹形tabel, 業務需求的情況下必須要實現,操作勾選資料編輯

這裡我們可以用兩個事件來實現:

  select:使用者勾選某行觸發事件,第一個引數selection:所有選中的資料, 第二引數row:勾選的這行資料)

  select-all : 表頭的全選、反選觸發事件,只有一個引數selection:所有選中的資料

1、多選的處理函式(文件例項):

toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
      // toggleRowSelection有兩個引數,第一個是每個選中資料,第二個是點選勾選的這行是否選中,樹形結構需要,不然子集選中,本身不給選中
this.$refs.multipleTable.toggleRowSelection(row, true); }); } else { this.$refs.multipleTable.clearSelection(); } },

2、現在再來處理多選和單選,呼叫toggleSelection 即可

因為樹形結構的資料結構不用,因此需要進行過濾處理

<el-table 
:data="tableData"
ref="multipleTable"
row-key="id"
:tree-props="{children: 'children}"
@select="rowSelect"
@select-all="selectAll"
align="center"
border>
  <el-table-column type="selection" width="55"></el-table-column>
  ...
</el-talbe>
// 模擬資料來源 
data = {
  list: [
    {
      "id": "11",
      
"country": "Australia", "enable": "1", "children": [ { "id": "151", "country": "Capital", "enable": "1" }, { "id": "152", "country": "Territory", "enable": "0", }, { "id": "153", "country": "Northern Territory", "enable": "0" }, { "id": "154", "country": "Queensland", "enable": "1" }, { "id": "155", "country": "South Australia", "enable": "1" } ] }, { "id": "58", "country": "Austria", "enable": "1" }, { "id": "331", "country": "Azores", "enable": "0" } ], message: "success", status: 200 }

簡單的template 結構和模擬的資料來源差不多,如上所示,children 包裹分層級

3、過濾函式 filterSelect, 選中的多層級需要處理資料才能實現正確的互動,即將層級裡面children的資料依次取出來,組成陣列

  filterSelect(selection) {
      let arr = [];
    // 迴圈children取值
function filterData(val){ arr.push(val) if (val.children) { val.children.map(item => { filterData(item) }) } }     // 源資料中取出選中的資料 this.tableData.map(item => { selection.map(val => { if (val.id === item.id) { filterData(val) } }) }) return arr }

4、實現符合邏輯的勾選互動

表頭全選函式:

    selectAll(selection) {
      let arr = this.filterSelect(selection)
      // 正反選, 過濾後有值勾選,空值清除所有,
      if (arr.length) {
        this.toggleSelection(arr)
      } else {
        // 清除所有
        this.$refs.multipleTable.clearSelection(selection);
      }
    }

單行(多層級)全選、單選:

    rowSelect(selection, row) {
      let selectArr = []
      if (selectArr.indexOf(row) === -1) {
        selectArr = this.filterSelect(selection)
        // 正反選, 過濾後有值勾選,空值清除所有,
        if (selectArr.length) {
          this.toggleSelection(selectArr)
        } else {
          // 清除所有
          this.$refs.multipleTable.clearSelection(selection);
        }
      }
    }

以上就可以實現多選樹形結構的操控

注: 如有需要參考的,請注意源資料模型和template結構中的引數配置,全選(多層級)、單選、過濾這三個函式,注意裡面的資料來源變數名this.tableData