parent.ts 437 B

12345678910111213141516171819202122
  1. import { getCurrentInstance } from "vue";
  2. /**
  3. * 获取父组件
  4. * @param name 组件名称
  5. * @example useParent<ClFormComponentPublicInstance>("cl-form")
  6. * @returns 父组件
  7. */
  8. export function useParent<T>(name: string): T | null {
  9. const { proxy } = getCurrentInstance()!;
  10. let p = proxy?.$parent;
  11. while (p != null) {
  12. if (p.$options.name == name) {
  13. return p as T | null;
  14. }
  15. p = p.$parent;
  16. }
  17. return p as T | null;
  18. }