vue获取组件实例对象

1.向上找到最近的指定组件

function findParentComponent (self, componentName) {
  let parent = self.$parent;
  let name = parent.$options.name;

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

2.向上找到所有的指定组件

function findParentsComponent (self, componentName) {
  let parents = [];
  const parent = self.$parent;

  if (parent) {
    if (parent.$options.name === componentName) parents.push(parent);
    return parents.concat(this.findParentsComponent(parent, componentName));
  } else {
    return [];
  }
}

3.向下找到最近的指定组件

function findChildrenComponent (self, componentName) {
  const childrens = self.$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 = this.findChildrenComponent(child, componentName);
        if (children) break;
      }
    }
  }
  return children;
}

4.向下找到所有指定的组件

function findChildrensComponent (self, componentName) {
  return self.$children.reduce((components, child) => {
    if (child.$options.name === componentName) components.push(child);
    const foundChilds = this.findChildrensComponent(child, componentName);
    return components.concat(foundChilds);
  }, []);
}

5.找到指定组件的兄弟组件

function findBrothersComponents (self, componentName, exceptMe = true) {
  let res = self.$parent.$children.filter(item => {
    return item.$options.name === componentName;
  });
  let index = res.findIndex(item => item._uid === self._uid);
  if (exceptMe) res.splice(index, 1);
  return res;
}
posted @   亘古不变  阅读(2)  评论(0编辑  收藏  举报  
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 使用C#创建一个MCP客户端
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示