項(xiàng)目中根據(jù)子節(jié)點(diǎn) id 展開(kāi)異步樹(shù)節(jié)點(diǎn)最易,需要后端返回當(dāng)前子節(jié)點(diǎn)的父級(jí)節(jié)點(diǎn) id 集合
<el-tree
:data="rootNodeData"
class="catalogTree"
ref="catalogTree"
highlight-current
node-key="id"
lazy
:load="treeLoadNode">
</el-tree>
data(){
return {
rootNodeData: [],
nodeZero: null,
resolveZero: null,
loading: false
}
},
methods: {
/**
* 目錄懶加載
* @param {Object} node
* @param {Object} resolve
*/
treeLoadNode(node, resolve){
// 開(kāi)啟 “加載中” 動(dòng)畫(huà)
if(node.level == 0) this.loading = true;
this.$axios.getTreeData({
pid: node.level === 0 ? 0 : node.data.id
}).then(res => {
// 請(qǐng)求接口羞海,返回?cái)?shù)據(jù)
let data = res.data.data;
// 暫存 方法參數(shù),以便手動(dòng)調(diào)用 此方法
if(node.level == 0){
this.nodeZero = node;
this.resolveZero = resolve;
this.rootNodeData = data; // 根節(jié)點(diǎn)賦值
}else{
// 渲染樹(shù)
resolve(data);
}
this.loading = false;
this.$nextTick(() => {
// 循環(huán)展開(kāi)節(jié)點(diǎn)
let pidList = data.pidList;
for (let i = 0; i < pidList.length; i++) { // 循環(huán)當(dāng)前節(jié)點(diǎn)所有pid集合
for (let j = 0; j < node.childNodes.length; j++) { // 循環(huán)子節(jié)點(diǎn)
// 查找相同id節(jié)點(diǎn)使之其一層一層展開(kāi)
if (pidList[i + 1] == node.childNodes[j].data.id) {
node.childNodes[j].expand(); // 會(huì)重新調(diào)用 懶加載方法 treeLoadNode
break;
}
}
}
let paramsId = this.$route.query.id ? this.$route.query.id : data[0].id;
// 根據(jù) id 獲取節(jié)點(diǎn)信息
let getNodeById = this.$refs.catalogTree.getNode(paramsId);
if(getNodeById){
// 設(shè)置節(jié)點(diǎn)選中
this.$refs.catalogTree.setCurrentKey(paramsId);
// 并跳轉(zhuǎn)
if(!this.$route.query.id) this.$router.replace({ path: this.$route.path, query: { id: paramsId }});
// 設(shè)置面包屑二級(jí)
this.breadCrumbData.levelTwo = getNodeById.data.name;
// 設(shè)置 localStorage
this.$ls.set('kbTreeNode', getNodeById.data);
}
})
})
}
}