yangsirgo / good-good-study

水平垂直居中,这是一道面试必考题,^_^
0 stars 0 forks source link

iview里面组件工具 #6

Open yangsirgo opened 5 years ago

yangsirgo commented 5 years ago

$emit 用于父子事件传递时使用,在组件嵌套组件的情况下并不适用。 iview里面的代码:

        dispatch(componentName, eventName, params) {
            let parent = this.$parent || this.$root;
            let name = parent.$options.name;
           //parent 组件有值 name 为空 或者name 的值 不等于 组件的名称,循环继续。
            while (parent && (!name || name !== componentName)) {
                parent = parent.$parent;

                if (parent) {
                    name = parent.$options.name;
                }
            }
            if (parent) {
                parent.$emit.apply(parent, [eventName].concat(params));
            }
        }

这段代码试用于非父子组件数据传递。从子孙组件往上发送事件。

function broadcast(componentName, eventName, params) {
    this.$children.forEach(child => {
        const name = child.$options.name;

        if (name === componentName) {
            child.$emit.apply(child, [eventName].concat(params));
        } else {
            // todo 如果 params 是空数组,接收到的会是 undefined
            broadcast.apply(child, [componentName, eventName].concat([params]));
        }
    });
}

这段代码试用于非父子组件数据传递。从父亲爷爷辈的组件往下发送事件。

yangsirgo commented 5 years ago
            compileFlatState () { // so we have always a relation parent/children of each node
                let keyCounter = 0;
                let childrenKey = ‘childrens’;
                const flatTree = [];
                function flattenChildren(node, parent) {
                    node.nodeKey = keyCounter++;
                    flatTree[node.nodeKey] = { node: node, nodeKey: node.nodeKey };
                    if (typeof parent != 'undefined') {
                        flatTree[node.nodeKey].parent = parent.nodeKey;
                        flatTree[parent.nodeKey][childrenKey].push(node.nodeKey);
                    }
                    if (node[childrenKey]) {
                        flatTree[node.nodeKey][childrenKey] = [];
                        node[childrenKey].forEach(child => flattenChildren(child, node));
                    }
                }
                this.stateTree.forEach(rootNode => {
                    flattenChildren(rootNode);
                });
                return flatTree;
            }

将深入的树形结构,给变成同级数组形式。

[{ 
id:'1',
childrens :[{
    id:"2"
}] 
}]

更改为:

[{ 
id:'1',
node:0,
childrens :[{
    id:"2"
}] 
},{
  node:1,
  id:2
}]