JAVASCRIPT
Dynamic and Asynchronously Loaded Components
Efficiently load and render components dynamically in Vue 3 using the <component :is="..." /> tag and defineAsyncComponent for lazy loading, improving application performance and flexibility.
// components/ComponentA.vue
<template><div>This is Component A</div></template>
<script setup> console.log('ComponentA loaded'); </script>
// components/ComponentB.vue
<template><div>This is Component B</div></template>
<script setup> console.log('ComponentB loaded'); </script>
// src/App.vue
<template>
<div>
<button @click="currentComponent = 'ComponentA'">Show A</button>
<button @click="currentComponent = 'ComponentB'">Show B</button>
<button @click="currentComponent = 'AsyncComponent'">Show Async</button>
<Transition name="fade" mode="out-in">
<component :is="currentComponent" />
</Transition>
</div>
</template>
<script setup>
import { ref, defineAsyncComponent } from 'vue';
import ComponentA from './components/ComponentA.vue';
import ComponentB from './components/ComponentB.vue';
const AsyncComponent = defineAsyncComponent(() =>
import('./components/AsyncComponent.vue')
);
const currentComponent = ref(ComponentA);
// To use string names, you need to register components globally or locally
// For simplicity here, we use component objects directly.
// If you prefer strings, you'd define:
// const componentsMap = {
// 'ComponentA': ComponentA,
// 'ComponentB': ComponentB,
// 'AsyncComponent': AsyncComponent
// };
// currentComponent = ref('ComponentA');
// then :is="componentsMap[currentComponent]"
</script>
<style>
.fade-enter-active, .fade-leave-active {
transition: opacity 0.5s ease;
}
.fade-enter-from, .fade-leave-to {
opacity: 0;
}
</style>
// components/AsyncComponent.vue (create this file)
<template><div>This is an Asynchronously Loaded Component.</div></template>
<script setup> console.log('AsyncComponent loaded'); </script>
How it works: This snippet illustrates how to render components dynamically and asynchronously in Vue 3. The `<component :is="currentComponent" />` tag allows switching between components based on the `currentComponent` reactive variable. `defineAsyncComponent` is used to lazily load `AsyncComponent.vue` only when it's needed, which improves initial page load performance. A `<Transition>` component is also wrapped around the dynamic component to provide a smooth fade effect during component changes, enhancing the user experience.