index.ts 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. import { shallowRef } from 'vue'
  2. import { flattedChildren, isVNode } from '@element-plus/utils'
  3. import type { ComponentInternalInstance, VNode } from 'vue'
  4. const getOrderedChildren = <T>(
  5. vm: ComponentInternalInstance,
  6. childComponentName: string,
  7. children: Record<number, T>
  8. ): T[] => {
  9. const nodes = flattedChildren(vm.subTree).filter(
  10. (n): n is VNode =>
  11. isVNode(n) &&
  12. (n.type as any)?.name === childComponentName &&
  13. !!n.component
  14. )
  15. const uids = nodes.map((n) => n.component!.uid)
  16. return uids.map((uid) => children[uid]).filter((p) => !!p)
  17. }
  18. export const useOrderedChildren = <T extends { uid: number }>(
  19. vm: ComponentInternalInstance,
  20. childComponentName: string
  21. ) => {
  22. const children: Record<number, T> = {}
  23. const orderedChildren = shallowRef<T[]>([])
  24. const addChild = (child: T) => {
  25. children[child.uid] = child
  26. orderedChildren.value = getOrderedChildren(vm, childComponentName, children)
  27. }
  28. const removeChild = (uid: number) => {
  29. delete children[uid]
  30. orderedChildren.value = orderedChildren.value.filter(
  31. (children) => children.uid !== uid
  32. )
  33. }
  34. return {
  35. children: orderedChildren,
  36. addChild,
  37. removeChild,
  38. }
  39. }