最近項目使用到了異步樹,異步樹的存在是解決樹型結構下數據過多的問題而誕生的,即點一次加載一次
多選異步樹
html
<el-tree
ref="tree"
:props="props"
node-key="userIndexCode"
:load="loadNode"
:highlight-current="false"
lazy
show-checkbox
@check-change="handleCheckChange">
</el-tree>
props
配置選項
node-key
每個樹節點用來作為唯一標識的屬性
:load
加載子樹數據的方法
:highlight-current
是否高亮當前選中節點
@check-change
節點選中狀態發生變化時的回調
一般說來,有上面幾個方法和參數就足夠構造樹了
JS
loadNode (node, resolve) {
// 判斷是否根節點
if (node.level === 0) {
API.getTree({ id: '-1' }).then((res) => {
// 發送請求返回結果
// 解析成標准的data結構
resolve(data)
})
} else {
API.getTree({ id: node.data.id }).then((res) => {
// 發送請求返回結果
// 解析成標准的data結構
// 這里的樹如果有部門和人員,需要在props里面加上 isLeaf: 'leaf' 本例中obj是節點,userobj是葉子節點
// 構造數組的時候 葉子節點 也需要加上leaf:true
resolve(obj.concat(userobj))
})
}
}
this.$refs.tree.getCheckedNodes()方法使用的坑
在實際使用中,發現如果節點下面有內容的話,this.$refs.tree.getCheckedNodes
可以正常使用
但是如果節點下面無內容而且選中的話,this.$refs.tree.getCheckedNodes(true,true)
會把節點也計算在內
針對這個組件問題,使用leaf
是否是葉子節點來過濾一次就可以了
this.$refs.tree.getCheckedNodes(true, true).map((value) => {
if (value.leaf) {
this.checkList.push(value)
}
})