All files / src/mixins tree.datasource.js

0% Statements 0/18
0% Branches 0/8
0% Functions 0/4
0% Lines 0/17

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43                                                                                     
export default {
    props: {
        parentField: String,
        childrenField: { type: String, default: 'children' },
        valueField: { type: String, default: 'value' },
    },
    methods: {
        listToTree(data) {
            const { valueField, parentField, childrenField } = this;
 
            // 避免引用关系导致数据错误
            data = data.map((item) => Object.assign({}, item));
 
            // Map记录一下
            const nodes = {}; // Record<id, { entity }>
            data.forEach((item) => {
                const id = this.$at(item, valueField);
                if (id) {
                    nodes[id] = item;
                }
            });
 
            const tree = [];
            data.forEach((item) => {
                const parentId = this.$at(item, parentField);
                const parent = nodes[parentId];
                // 没有parentId 或者 parent不存在的不处理
                if (!parentId || !parent) {
                    tree.push(item);
                } else {
                    if (!this.$at(parent, childrenField)) {
                        this.$setAt(parent, childrenField, []);
                    }
 
                    this.$at(parent, childrenField).push(item);
                }
            });
 
            return tree;
        },
    },
};