← Back to all snippets
JAVASCRIPT

Dynamic Components with Asynchronous Loading

Render components dynamically using `<component :is>` and improve performance with `defineAsyncComponent` for lazy loading in Vue 3 applications.

// component-a.vue
// <template><div>Component A Content</div></template>
// <script setup></script>

// component-b.vue
// <template><div>Component B Content</div></template>
// <script setup></script>

// App.vue
<template>
  <div>
    <button @click="currentComp = 'ComponentA'">Show A</button>
    <button @click="currentComp = 'ComponentB'">Show B</button>
    <button @click="currentComp = 'AsyncComponent'">Show Async</button>

    <hr />
    <KeepAlive>
      <component :is="currentComp" />
    </KeepAlive>
  </div>
</template>

<script setup>
import { ref, defineAsyncComponent } from 'vue';
import ComponentA from './component-a.vue';
// No direct import for ComponentB to simulate async loading (or if it's not always used)

// Define an async component using a dynamic import
const AsyncComponent = defineAsyncComponent(() =>
  import('./component-b.vue')
);

const currentComp = ref('ComponentA');

// Map component names to actual component objects
const components = {
  ComponentA,
  AsyncComponent // This will load when first rendered
  // You can also add ComponentB here if it's imported synchronously
  // ComponentB: defineAsyncComponent(() => import('./component-b.vue'))
};
</script>
How it works: This snippet showcases dynamic components in Vue 3 using `<component :is="currentComp" />`. The `currentComp` ref holds the name of the component to be rendered. It also demonstrates `defineAsyncComponent`, which allows components to be loaded lazily (on demand) rather than bundled into the initial JavaScript payload, improving application performance. The example uses `KeepAlive` around the dynamic component to preserve its state when switching between components, preventing re-renders and maintaining user input or scroll position.

Need help integrating this into your project?

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

Hire DigitalCodeLabs