美文网首页
vue 通过$parent 和$children找到对应的对象

vue 通过$parent 和$children找到对应的对象

作者: _嘿嘿_ | 来源:发表于2020-03-24 15:30 被阅读0次
    // Find components upward
    function findComponentUpward (context, componentName, componentNames) {
        if (typeof componentName === 'string') {
            componentNames = [componentName];
        } else {
            componentNames = componentName;
        }
    
        let parent = context.$parent;
        let name = parent.$options.name;
        while (parent && (!name || componentNames.indexOf(name) < 0)) {
            parent = parent.$parent;
            if (parent) name = parent.$options.name;
        }
        return parent;
    }
    export {findComponentUpward};
    
    // Find component downward
    export function findComponentDownward (context, componentName) {
        const childrens = context.$children;
        let children = null;
    
        if (childrens.length) {
            for (const child of childrens) {
                const name = child.$options.name;
                if (name === componentName) {
                    children = child;
                    break;
                } else {
                    children = findComponentDownward(child, componentName);
                    if (children) break;
                }
            }
        }
        return children;
    }
    
    // Find components downward
    export function findComponentsDownward (context, componentName) {
        return context.$children.reduce((components, child) => {
            if (child.$options.name === componentName) components.push(child);
            const foundChilds = findComponentsDownward(child, componentName);
            return components.concat(foundChilds);
        }, []);
    }
    
    // Find components upward
    export function findComponentsUpward (context, componentName) {
        let parents = [];
        const parent = context.$parent;
        if (parent) {
            if (parent.$options.name === componentName) parents.push(parent);
            return parents.concat(findComponentsUpward(parent, componentName));
        } else {
            return [];
        }
    }
    
    // Find brothers components
    export function findBrothersComponents (context, componentName, exceptMe = true) {
        let res = context.$parent.$children.filter(item => {
            return item.$options.name === componentName;
        });
        let index = res.findIndex(item => item._uid === context._uid);
        if (exceptMe) res.splice(index, 1);
        return res;
    }
    

    相关文章

      网友评论

          本文标题:vue 通过$parent 和$children找到对应的对象

          本文链接:https://www.haomeiwen.com/subject/zsmoyhtx.html