scopeId.ts 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import { isArray } from '@vue/shared'
  2. import { type VaporComponentInstance, isVaporComponent } from './component'
  3. import { getInheritedScopeIds } from '@vue/runtime-dom'
  4. import { isFragment } from './fragment'
  5. import type { Block } from './block'
  6. import { isInteropEnabled } from './vdomInteropState'
  7. export function setScopeId(block: Block, scopeIds: string[]): void {
  8. if (block instanceof Element) {
  9. for (const id of scopeIds) {
  10. block.setAttribute(id, '')
  11. }
  12. } else if (isVaporComponent(block)) {
  13. setScopeId(block.block, scopeIds)
  14. } else if (isArray(block)) {
  15. for (const b of block) {
  16. setScopeId(b, scopeIds)
  17. }
  18. } else if (isFragment(block)) {
  19. setScopeId(block.nodes, scopeIds)
  20. }
  21. }
  22. export function setComponentScopeId(instance: VaporComponentInstance): void {
  23. const { parent, scopeId } = instance
  24. if (!parent || !scopeId) return
  25. // prevent setting scopeId on multi-root fragments
  26. if (isArray(instance.block) && instance.block.length > 1) return
  27. const scopeIds: string[] = []
  28. const parentScopeId = parent && parent.type.__scopeId
  29. // if parent scopeId is different from scopeId, this means scopeId
  30. // is inherited from slot owner, so we need to set it to the component
  31. // scopeIds. the `parentScopeId-s` is handled in createSlot
  32. if (parentScopeId !== scopeId) {
  33. scopeIds.push(scopeId)
  34. } else {
  35. if (parentScopeId) scopeIds.push(parentScopeId)
  36. }
  37. // inherit scopeId from vdom parent
  38. if (
  39. isInteropEnabled &&
  40. parent.subTree &&
  41. (parent.subTree.component as any) === instance &&
  42. parent.vnode!.scopeId
  43. ) {
  44. scopeIds.push(parent.vnode!.scopeId)
  45. const inheritedScopeIds = getInheritedScopeIds(parent.vnode!, parent.parent)
  46. scopeIds.push(...inheritedScopeIds)
  47. }
  48. if (scopeIds.length > 0) {
  49. setScopeId(instance.block, scopeIds)
  50. }
  51. }