Skip to content

usePortal

This requires the following keys to be installed:

usePortal

ts
import type { Ref } from 'vue'
import { portalTargetInjectionKey } from '@/ui/keys/portal-target'
import { computed, inject, provide } from 'vue'

export function usePortal(portal: Ref<string | HTMLElement | boolean | undefined>) {
  const portalTarget = inject(portalTargetInjectionKey, undefined)

  const to = computed(() => {
    if (typeof HTMLElement === 'undefined') {
      return 'body'
    }

    if (typeof portal.value === 'string' || portal.value instanceof HTMLElement) {
      return portal.value
    }

    return portalTarget?.value ?? 'body'
  })

  const disabled = computed(() => typeof portal.value === 'boolean' ? !portal.value : false)

  provide(portalTargetInjectionKey, computed(() => to.value))

  return computed(() => ({
    to: to.value,
    disabled: disabled.value,
  }))
}
ts
import type { Ref } from 'vue'
import { portalTargetInjectionKey } from '@/UI/Keys/portal-target'
import { computed, inject, provide } from 'vue'

export function usePortal(portal: Ref<string | HTMLElement | boolean | undefined>) {
  const portalTarget = inject(portalTargetInjectionKey, undefined)

  const to = computed(() => {
    if (typeof HTMLElement === 'undefined') {
      return 'body'
    }

    if (typeof portal.value === 'string' || portal.value instanceof HTMLElement) {
      return portal.value
    }

    return portalTarget?.value ?? 'body'
  })

  const disabled = computed(() => typeof portal.value === 'boolean' ? !portal.value : false)

  provide(portalTargetInjectionKey, computed(() => to.value))

  return computed(() => ({
    to: to.value,
    disabled: disabled.value,
  }))
}