← Back to all snippets
JAVASCRIPT

Dynamically Loading and Asynchronously Importing Vue 3 Components

Learn how to dynamically render components based on data and asynchronously load them for better performance and code splitting in Vue 3 applications using `is` attribute and `defineAsyncComponent`.

// components/ComponentA.vue
<template><div>Component A Content</div></template>
<script setup></script>

// components/ComponentB.vue
<template><div>Component B Content</div></template>
<script setup></script>

// App.vue
<template>
  <div>
    <h1>Dynamic & Async Components</h1>

    <button @click="currentComp = 'ComponentA'">Show A</button>
    <button @click="currentComp = 'ComponentB'">Show B</button>
    <button @click="currentComp = 'AsyncComponent'">Show Async</button>

    <div class="dynamic-area">
      <component :is="currentComp"></component>
    </div>

    <hr/>

    <h2>Example with defineAsyncComponent</h2>
    <button @click="showLazyComponent = true">Load Lazy Component</button>
    <div v-if="showLazyComponent">
      <LazyLoadedComponent />
    </div>
  </div>
</template>

<script setup>
import { ref, defineAsyncComponent } from 'vue';

// Dynamic components
import ComponentA from './components/ComponentA.vue';
import ComponentB from './components/ComponentB.vue';

// Async component (lazy loaded)
const AsyncComponent = defineAsyncComponent(() =>
  import('./components/ComponentA.vue') // Example: loading ComponentA async
);

// Another way to use async component, useful for conditional rendering
const LazyLoadedComponent = defineAsyncComponent(() =>
  import('./components/ComponentB.vue')
);

const currentComp = ref('ComponentA');
const showLazyComponent = ref(false);

// Register components locally for <component :is="..."> to work with string names
const components = {
  ComponentA,
  ComponentB,
  AsyncComponent
};
</script>

<style>
.dynamic-area {
  border: 1px solid #ccc;
  padding: 15px;
  margin-top: 10px;
  min-height: 50px;
}
</style>
How it works: This snippet demonstrates two powerful Vue 3 features: dynamic components and asynchronous components. Dynamic components use the `<component :is="currentComponent">` syntax to render different components based on a reactive value (`currentComp`), which can be a component object or its registered name. Asynchronous components, created with `defineAsyncComponent`, are lazy-loaded only when they are needed, improving initial page load performance and enabling code splitting. This is shown by `AsyncComponent` and `LazyLoadedComponent` which are imported dynamically.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs