問題描述
el-table顯示樹形數據報錯
Error: for nested data item, row-key is required
TypeError: this.$el.querySelectorAll is not a function
問題分析
后端返回的樹形結構中沒有返回id字段,所以需要手動遍歷數據給數據添加id,el-table中默認設置row-key="id"
,沒有id,又沒有設置row-key的值這時就會報錯。
問題解決
遞歸數據
recursive(data) {
const setId = list => {
list.forEach(item => {
item.id = item.proid
if (item.children) {
setId(item.children)
}
})
}
setId(data)
},
el-table 樹形結構復選框子項勾選問題
在使用element做表格開發使用復選框和樹形結構時發現點擊父元素復選框時,子元素無法選中,於是在table上監聽點擊和全選,根據數據有子節點來手動切換選中與否。
// el-table 樹形復選框需要的屬性和方法
@select="select"
@select-all="selectAll"
@selection-change="selectionChange"
:tree-props="{children: 'children'}"
// 為選中行添加特定有樣式
:row-class-name="rowClassName"
// el-table 封住方法
// 單選 this.childNm 就是 tree-props中的children
select(selection, row) {
const checked = selection.some(el => {
return row.id === el.id
})
if (this.childNm && row[this.childNm]) {
this.recursive(row[this.childNm], checked)
} else {
row.isActive = checked
}
},
/**
* @Description: 遞歸渲染
*/
recursive(data, checked) {
const vm = this
const toggleSel = list => {
list.forEach(item => {
item.isActive = checked
vm.toggleSelection(item, checked)
if (item[this.childNm]) {
toggleSel(item[this.childNm])
}
})
}
toggleSel(data)
},
/**
* @Description: 全選
*/
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) {
this.recursive(selection, true)
}
if (isCancel) {
this.recursive(this.tableData, false)
}
},
/**
* @Description: 切換選中狀態
*/
toggleSelection(row, select) {
if (row) {
this.$nextTick(() => {
this.$refs.DeTable && this.$refs.DeTable.toggleRowSelection(row, select)
})
}
},
// 選中行后添加樣式
rowClassName({ row }) {
if (row.isActive) {
return 'mark-color'
}
},
// 調用封裝的table組件返顯數據
/**
* @Description: 遞歸回顯
* @param {*} data
* @param {*} selIds 返顯需要的id集合
* @return {*}
*/
recursiveBack(data, selIds) {
const tableRef = this.$refs.tableRef
this.expandKeys = []
const toggleSel = list => {
list.forEach(item => {
item.isActive = selIds.includes(item.id) // 返顯標志
tableRef && tableRef.toggleSelection(item, item.isActive) // 更新table數據
this.expandKeys.push(item.id) // 展開
if (item.children) {
toggleSel(item.children)
}
})
}
toggleSel(data)
},
備注
-
row-key: 渲染樹形數據時,必須要指定 row-key, row-key的值必須是唯一的,可以是String類型,也可以是function(row)
-
indent: 展示樹形數據時,樹節點的縮進, Number類型
-
tree-props: 渲染嵌套數據的配置選項。:tree-props="{children: 'children'}"定義子項的List名字,在data內寫入,即可將子項寫入在表格中
-
select-on-indeterminate:在多選表格中,當僅有部分行被選中時,點擊表頭的多選框時的行為。若為 true,則選中所有行;若為 false,則取消選擇所有行
-
toggleRowSelection:用於多選表格,切換某一行的選中狀態,如果使用了第二個參數,則是設置這一行選中與否(selected 為 true 則選中)
-
clearSelection:用於多選表格,清空用戶的選擇