#Dynamic import loop
1 messages · Page 1 of 1 (latest)
The behavior you're describing is related to how Nuxt handles component registration and dynamic components. Let me explain the reasons behind this:
-
Auto-imported components:
Nuxt automatically imports components from thecomponents/directory, but this auto-import feature works at build time Docs > Guide > Directory-structure > components (https://nuxt.com/docs/guide/directory-structure/components). When you use a component directly in your template, Nuxt can detect and import it. However, when you use a string to dynamically reference a component, Nuxt cannot automatically resolve this at build time. -
Dynamic components with
:is:
When using the<component :is="...">syntax, Vue needs to resolve the component at runtime. If you pass a string to:is, Vue looks for a globally registered component with that name Docs > Guide > Directory-structure > components > Dynamic Components Part 1 (https://nuxt.com/docs/guide/directory-structure/components#dynamic-components). -
Global registration:
Components can be registered globally in Nuxt, which makes them available throughout your application without explicit imports. This is why your second example works when the components are globally registered Stack Overflow Post > Nuxt3 dynamic <component> Part 3 (https://stackoverflow.com/questions/78319986).
To make your second example work without global registration, you have a few options:
- Use
resolveComponent:
<script setup>
import { resolveComponent } from 'vue'
const components = [
resolveComponent('Foo'),
resolveComponent('Bar')
]
</script>
<template>
<ul>
<li v-for="(c, i) in components" :key="i">
<component :is="c" />
</li>
</ul>
</template>
- Import components directly:
<script setup>
import { Foo, Bar } from '#components'
const components = [Foo, Bar]
</script>
3. Use the `Lazy` prefix for dynamic imports:
```vue
<template>
<ul>
<li v-for="(c, i) in ['Foo', 'Bar']" :key="i">
<component :is="`Lazy${c}`" />
</li>
</ul>
</template>
The Lazy prefix tells Nuxt to create a dynamic import for the component Docs > Guide > Directory-structure > components > Dynamic Components Part 1 (https://nuxt.com/docs/guide/directory-structure/components#dynamic-components).
Remember, while global registration can make your second example work, it's generally not recommended to register all components globally due to potential performance issues Stack Overflow Post > Nuxt3 dynamic <component> Part 3 (https://stackoverflow.com/questions/78319986).
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
@hollow jetty Kapa.ai is still learning and improving, please let me know how I did by reacting below.