NuxtN
Nuxt7mo ago
29 replies
Reinier Kaper

Auto imports and `<component :is="" />`

I'm struggling with a dynamic part of our app, where we load components based on what button a user clicks. Pretty straightforward, but we use constants with types a lot to make things easy, but I can't figure out how to do it with dynamic components.

Pseudo-code:
// In constants/calendars.ts
import { CalendarPreferences, CalendarFoo } from '#components'
export const CALENDAR_COMPONENTS = {
  PREFERENCES: CalendarPreferences,
  FOO: CalendarFoo,
} as const
Object.freeze(CALENDAR_COMPONENTS)
export type CALENDAR_COMPONENTS = (typeof CALENDAR_COMPONENTS)[keyof typeof CALENDAR_COMPONENTS]


// In a child component
<CalendarControl
  :heading="t('availability.rentalSeason')"
  :subheading="legibileSeason ?? t('availability.rentalSeasonPlaceholder')"
  @click="selectComponent(CALENDAR_COMPONENTS.FOO)" // Select CalendarFoo to mount in parent
/>

const emit = defineEmits<{
  selectComponent: [component: keyof CALENDAR_COMPONENTS]
}>()

function selectComponent(component: keyof CALENDAR_COMPONENTS) {
  emit('selectComponent', component)
}


// In parent
function handleSelectControl(control: keyof CALENDAR_COMPONENTS) {
  currentComponent.value = CALENDAR_COMPONENTS[control as keyof typeof CALENDAR_COMPONENTS]
}

<component
  :is="currentComponent"
  @select-control="handleSelectControl"
/>


I'm wondering what a sane approach is here, but so far I'm just running into type issues 😦
Was this page helpful?