useParent.ts 853 B

1234567891011121314151617181920212223242526272829303132333435
  1. import { inject, computed, onUnmounted, getCurrentInstance, ComponentPublicInstance, ComponentInternalInstance } from 'vue';
  2. type ParentProvide<T> = T & {
  3. link(child: ComponentInternalInstance): void;
  4. unlink(child: ComponentInternalInstance): void;
  5. children: ComponentPublicInstance[];
  6. internalChildren: ComponentInternalInstance[];
  7. };
  8. export function useParent<T>(key: string | symbol) {
  9. const parent = inject<ParentProvide<T> | null>(key, null);
  10. if (parent) {
  11. const instance = getCurrentInstance();
  12. if (instance) {
  13. const { link, unlink, internalChildren, ...rest } = parent;
  14. link(instance);
  15. onUnmounted(() => {
  16. unlink(instance);
  17. });
  18. const index = computed(() => internalChildren.indexOf(instance));
  19. return {
  20. parent: rest,
  21. index
  22. };
  23. }
  24. }
  25. return {};
  26. }