vue中组件通信之findComponents

时间:2020-8-1 作者:admin
// 向上查找组件 context为当前组件上下文对象,componentName为组件名
const findUpwardComponent = (context, componentName) => {
    let parent = context.$parent
    let name = parent.$options.name
    while (parent && (!name || !name.includes(componentName))) {
        parent = parent.$parent
        if (parent) name = parent.$options.name
    }
    return parent
}

// 查找兄弟组件
const findBrotherComponents = (ctx, componentName, exceptMe = true) => {
    const $brothers = ctx.$parent.$children.filter(item => {
        return item.$options.name && item.$options.name.includes(componentName)
    })
    const index = $brothers.findIndex(item => item._uid === ctx._uid)
    if (exceptMe && index > -1) $brothers.splice(index, 1)
    return $brothers
}

// 向下查找
const findDownwardComponent = (context, componentName) => {
    const $children = context.$children
    let bean = null
    if ($children.length) {
        for (const child of $children) {
            const name = child.$options.name
            if (name && name.includes(componentName)) {
                bean = child
                break
            } else {
                bean = findDownwardComponent(child, componentName)
                if (bean) break
            }
        }
    }
    return bean
}
声明:本文内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎进行举报,并提供相关证据,工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。