前提:項目表格是樹結構,增刪查改不能刷新整個表格,因爲官網關於樹結構表格的方法比較少,所以踩坑分享下
一、關於全選
坑:樹結構裏面它只勾選第一層的數據,子數據都是沒有勾選的
解決方法:@select-all=“selectAll” 寫個方法自己全選....不過這也是有坑的,這種方法只能在一次性拿到tableDatad的情況下使用。我試了異步加載樹結構好像沒拿到tableData,所以不能進行全選
代碼:
<el-table
ref="table"
:data="tableData"
style="width: 100%;margin-bottom: 20px;"
row-key="id"
border
default-expand-all
:select-on-indeterminate="true"
:tree-props="{children: 'childList', hasChildren: 'hasChildren'}"
@select-all="selectAll"
>
<el-table-column type="selection" width="55"></el-table-column>
</el-table>
selectAll(selection, first) {
if (!first) { // 判斷是不是第一次進來,第一次進來要把this.isAllSelect設置爲true或false,子數據循環就不需要
this.isAllSelect = !this.isAllSelect
}
selection.map(el => {
if (el.children) {
el.children.map(j => {
this.toggleSelection(j, this.isAllSelect)
})
if (el.children.length > 0) { // 判斷是否有子數據,有的話要進行循環
this.selectAll(el.children, true)
}
}
})
},
toggleSelection(row, select) { // 切換選擇,select爲true就是選擇,false爲不選
if (row) {
this.$nextTick(() => {
this.$refs.multipleTable &&
this.$refs.multipleTable.toggleRowSelection(row, select)
})
}
}
二、關於增改
因爲我是一次性拿到tableData的,所以直接在數據上進行操作的
代碼:
addData(info) { // 點添加調用改方法,後臺返回對象info(添加的數據)
if (info.groupId) {
this.renderAndAdd(this.tableData[0], info)
} else {
this.tableData[0].children.unshift(info)
}
},
updData(info) { // 更新的話是先刪掉舊數據,再添加一條,因爲有可能添加到別的父數據下面
this.renderAndUpd(this.tableData[0], info)
this.addData(info)
},
renderAndAdd(data, info) { // 遍歷尋找父數據
if (data.id === info.groupId) {
data.children.unshift(info)
this.$refs.multipleTable.toggleRowExpansion(data, true) // 添加完還要打開添加的父數據
} else {
data.children.forEach(element => {
if (element.type === 'group') {
this.renderAndAdd(element, info)
}
})
}
},
renderAndUpd(data, info) { // 刪掉舊數據
if (data.type === 'group' || data.type === 'rootdomain') {
data.children.forEach((element, index) => {
if (element.id === info.id) {
data.children.splice(index, 1)
// this.$set(data.children, index, info)
}
this.renderAndUpd(element, info)
})
}
},
如果是異步加載數據的話,可以再調用load方法,先把調用load方法的node和resolve存起來,添加或修改之後再調用一次,不過後面我想覺得不可行,萬一打開之後又跑到別的父數據下面去修改,就可能加載不到