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

  1. /**
  2. * context 当前组件,componentName 需要查找的组件名称
  3. */
  4. function findComponentUpward (context, componentName) {
  5. let parent = context.$parent;
  6. let name = parent.$options.name;
  7. while (parent && (!name || [componentName].indexOf(name) < 0)) {
  8. parent = parent.$parent;
  9. if (parent) name = parent.$options.name;
  10. }
  11. return parent;
  12. }

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

  1. function findComponentsUpward (context, componentName) {
  2. let parents = [];
  3. const parent = context.$parent;
  4. if (parent) {
  5. if (parent.$options.name === componentName) parents.push(parent);
  6. return parents.concat(findComponentsUpward(parent, componentName));
  7. } else {
  8. return [];
  9. }
  10. }

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

  1. function findComponentDownward (context, componentName) {
  2. const childrens = context.$children;
  3. let children = null;
  4. if (childrens.length) {
  5. for (const child of childrens) {
  6. const name = child.$options.name;
  7. if (name === componentName) {
  8. children = child;
  9. break;
  10. } else {
  11. children = findComponentDownward(child, componentName);
  12. if (children) break;
  13. }
  14. }
  15. }
  16. return children;
  17. }

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

  1. function findComponentsDownward (context, componentName) {
  2. return context.$children.reduce((components, child) => {
  3. if (child.$options.name === componentName) components.push(child);
  4. const foundChilds = findComponentsDownward(child, componentName);
  5. return components.concat(foundChilds);
  6. }, []);
  7. }

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

  1. function findBrothersComponents (context, componentName, exceptMe = true) {
  2. let res = context.$parent.$children.filter(item => {
  3. return item.$options.name === componentName;
  4. });
  5. let index = res.findIndex(item => item._uid === context._uid);
  6. if (exceptMe) res.splice(index, 1);
  7. return res;
  8. }