JavaScript is required for this page to work.
⤎ Back to blog overview

Dynamic use of components in Nuxt requires manual imports

Just a very brief post about something that confused me a bit when I first needed it. That is dynamically switching between components in Nuxt.

In Vue (or Nuxt) you can dynamically pick HTML tags using the very handy is attribute. This example will render either an h1 or an h2.

Vue
<script setup>
const somethingToEvaluate = true
const headingTag = somethingToEvaluate ? 'h1' : 'h2'
</script>

<template>
  <component :is="headingTag">I am a heading</component>
</template>

Like with HTML tags, you can also do the same for components. However, although Nuxt does provide auto-imports for components out of the box, imports are required in cases where you are using the is attribute. So if we had a component called MyHeadingComponent.vue and it looked something like this:

Vue
<template>
  <h1>
    <slot />
  </h1>
</template>

We would need to import the component first to be able to use it dynamically.

Vue
<script setup>
import MyHeadingComponent from '~/components/MyHeadingComponent.vue'
const somethingToEvaluate = true
const headingTag = somethingToEvaluate ? MyHeadingComponent : 'h2'
</script>

<template>
  <component :is="headingTag">I am a heading</component>
</template>

If you do not include the import, you might end up with something like this in your DOM.

<mycomponent>I am a heading</mycomponent>

For more in-depth material on this topic, watch this video called Dynamic Components in Vue by Alex Lichter on his fantastic YouTube channel.