JAVASCRIPT

Render Dynamic and Asynchronous Components in Vue 3

Learn to dynamically switch between different Vue components at runtime and implement lazy loading for components to optimize performance.

// components/TabA.vue
<template>
  <div>Content for Tab A</div>
</template>

// components/TabB.vue
<template>
  <div>Content for Tab B</div>
</template>

// App.vue
<script setup>
import { ref, defineAsyncComponent, computed } from 'vue';

// Synchronous imports for demonstration
import TabA from './components/TabA.vue';
// Asynchronous import for lazy loading (recommended for larger components)
const TabB = defineAsyncComponent(() => import('./components/TabB.vue'));

const currentTab = ref('TabA'); // Holds the name of the current component to display

const tabs = {
  TabA,
  TabB
};

// Helper to get the component based on currentTab value
const currentTabComponent = computed(() => tabs[currentTab.value]);
</script>

<template>
  <div>
    <button @click="currentTab = 'TabA'">Show Tab A</button>
    <button @click="currentTab = 'TabB'">Show Tab B</button>

    <keep-alive>
      <component :is="currentTabComponent"></component>
    </keep-alive>
  </div>
</template>
How it works: Vue 3 allows dynamic component rendering using the `<component :is="ComponentName"></component>` syntax, where `ComponentName` is either a component object or a string representing a globally registered component. This snippet shows how to switch between `TabA` and `TabB` components. It also demonstrates `defineAsyncComponent`, which enables lazy loading of components, improving initial load times by fetching component code only when needed. `keep-alive` is used to preserve the state of dynamic components when switching between them.

Need help integrating this into your project?

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

Hire DigitalCodeLabs