当前需求:层级列表中选中某个元素,则获取最底层子集id,并用逗号连接(1,2,3,4,5);
数据形式:
let data = [{
id:"1",
children:[{
id:"11",
children:[{
id:"111",
children:null
},
{
id:"112",
children:null
},
{
id:"113",
children:null
}]
},
{
id:"12",
children:[{
id:"121",
children:null
},
{
id:"122",
children:null
},
{
id:"123",
children:null
}]
}]
}];
遍历方法可参考:https://blog.csdn.net/chaos_h…,写的很详细
具体操作:首先找到选择元素的id在树形数据中的位置,并获取他
找寻id相同的的元素
findSameId(tree, id) {
let isGet = false;
let retNode = null;
function deepSearch(tree, id) {
for (var i = 0; i < tree.length; i++) {
if (tree[i].children && tree[i].children.length > 0) {
deepSearch(tree[i].children, id);
}
if (id === tree[i].id || isGet) {
isGet || (retNode = tree[i]);
isGet = true;
break;
}
}
}
deepSearch(tree, id);
return retNode;
};
找寻他的最底层子元素,也就是所有没有子集的元素
找当前id的子元素的id
findChildId(data) {
console.log(data, 678);
console.log(data.children, 678);
if (data.children !== null) {
for (let i = 0; i < data.children.length; i++) {
console.log(data.children[i], i);
const childrens = data.children[i];
if (childrens.hasOwnProperty("children") && childrens.children && childrens.children.length !== 0) {
console.log('-------');
console.log(childrens, i);
console.log('-------');
this.findChildId(childrens);
} else {
this.sideIds.push(childrens.id);
}
}
} else {
this.sideIds.push(data.id);
}
}
### 由于本身是vue下的处理 handleSelectDept是触发点击获取到对应id; this.sideIds是本身在data里里定义了的
data(){
return{
sideIds:[]
}
}
触发效果
handleSelectDept(key) {
this.sideIds = [];//每次点击需要把本身的sideIds清空
const dataId = this.findSameId(this.treeData, key);
this.findChildId(dataId);
console.log(this.sideIds, 9999)
this.$set(this.queryForm, 'depIds', this.sideIds.join(","));
console.log(this.queryForm, 989);
this.getTableData();
}