el-table树形结构的复选

el-table树形结构的复选

在element-ui 2.13中,树形表格加复选框后,子结构无法选中的问题。于是在table上监听点击和全选,根据数据有子节点来手动切换选中与否。
template如下:

  
    
    
    
    
    
    
    
    
  
  {{ selectArr.map(el => el.id) }}
  
取消选择

data如下

  tableData: [{
      id: 1,
      date: '2016-05-01',
      name: '王小虎',
      address: '上海市普陀区金沙江路 1518 弄'
    }, {
      id: 2,
      date: '2016-05-02',
      name: '王小虎',
      address: '上海市普陀区金沙江路 1517 弄'
    }, {
      id: 3,
      date: '2016-05-03',
      name: '王小虎',
      address: '上海市普陀区金沙江路 1519 弄',
      childList: [{
          id: 31,
          date: '2016-05-31',
          name: '王小虎',
          address: '上海市普陀区金沙江路 1519 弄'
        }, {
          id: 32,
          date: '2016-05-32',
          name: '王小虎',
          address: '上海市普陀区金沙江路 1519 弄'
      }]
    }, {
      id: 4,
      date: '2016-05-04',
      name: '王小虎',
      address: '上海市普陀区金沙江路 1516 弄'
    }],
  selectArr: []

script代码如下

select (selection, row) {
  if (selection.some(el => { return row.id === el.id })) {
    if (row.childList) {
      row.childList.map(j => {
        this.toggleSelection(j, true)
      })
    }
  } else {
    if (row.childList) {
      row.childList.map(j => {
        this.toggleSelection(j, false)
      })
    }
  }
},
selectAll (selection) {
  // tabledata第一层只要有在selection里面就是全选
  const isSelect = selection.some(el => {
    const tableDataIds = this.tableData.map(j => j.id)
    return tableDataIds.includes(el.id)
  })
  // tableDate第一层只要有不在selection里面就是全不选
  const isCancel = !this.tableData.every(el => {
    const selectIds = selection.map(j => j.id)
    return selectIds.includes(el.id)
  })
  if (isSelect) {
    selection.map(el => {
      if (el.childList) {
        el.childList.map(j => {
          this.toggleSelection(j, true)
        })
      }
    })
  }
  if (isCancel) {
    this.tableData.map(el => {
      if (el.childList) {
        el.childList.map(j => {
          this.toggleSelection(j, false)
        })
      }
    })
  }
},
selectionChange (selection) {
  this.selectArr = selection
},
toggleSelection (row, select) {
  if (row) {
    this.$nextTick(() => {
      this.$refs.table && this.$refs.table.toggleRowSelection(row, select)
    })
  }
},
cancelAll () {
  this.$refs.table.clearSelection()
}

有个问题手动切换选中会多次切换表格的selection-change,
满足了基本效果,希望有其他方法的留言
el-table树形结构的复选_第1张图片

你可能感兴趣的:(element-ui,vue.js,table)