Vue树形数据处理js

14次阅读

共计 1529 个字符,预计需要花费 4 分钟才能阅读完成。

当前需求: 层级列表中选中某个元素, 则获取最底层子集 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();}

正文完
 0