找到任意组件实例的方法

找到任意组件实例的方法

由一个组件,向上找到最近的指定组件

/**
 * 由一个组件,向上找到最近的指定组件
 * @param {*} context 当前上下文,比如你要基于哪个组件来向上寻找,一般都是基于当前的组件,也就是传入 this
 * @param {*} componentName 要找的组件的 name
 */
function findComponentUpward(context, componentName) {
  let parent = context.$parent
  let name = parent.$options.name

  while (parent && (!name || [componentName].indexOf(name) < 0)) {
    parent = parent.$parent
    if (parent) name = parent.$options.name
  }
  return parent
}

由一个组件,向上找到所有的指定组件

/**
 * 由一个组件,向上找到所有的指定组件
 * @param {*} context 当前上下文,比如你要基于哪个组件来向上寻找,一般都是基于当前的组件,也就是传入 this
 * @param {*} componentName 要找的组件的 name
 */
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 []
  }
}

由一个组件,向下找到最近的指定组件

/**
 * 由一个组件,向下找到最近的指定组件
 * @param {*} context 当前上下文,比如你要基于哪个组件来向上寻找,一般都是基于当前的组件,也就是传入 this
 * @param {*} componentName 要找的组件的 name
 */
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
}

由一个组件,向下找到所有指定的组件

/**
 * 由一个组件,向下找到所有指定的组件
 * @param {*} context 当前上下文,比如你要基于哪个组件来向上寻找,一般都是基于当前的组件,也就是传入 this
 * @param {*} componentName 要找的组件的 name
 */
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)
  }, [])
}

由一个组件,找到指定组件的兄弟组件

/**
 * 由一个组件,找到指定组件的兄弟组件
 * @param {*} context 当前上下文,比如你要基于哪个组件来向上寻找,一般都是基于当前的组件,也就是传入 this
 * @param {*} componentName 要找的组件的 name
 * @param {*} exceptMe 是否把本身除外
 */
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
}

本文章由作者搜集整理,并非原创

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值