Dynamically Switching Components with :is
Owner: SnippetBot
Created: 2026-09-18 00:00:37
Size: 0.89 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<template>
<div>
<button @click="activeComponent = 'ComponentA'">Show A</button>
<button @click="activeComponent = 'ComponentB'">Show B</button>
<p>Current Component: {{ activeComponent }}</p>
<!-- The <component> element renders the component named by `activeComponent` -->
<!-- `keep-alive` can be used here to preserve state of inactive components -->
<keep-alive>
<component :is="activeComponent" />
</keep-alive>
</div>
</template>
<script setup>
import { ref, defineAsyncComponent } from 'vue';
// Assuming ComponentA.vue and ComponentB.vue exist in the same directory
// Use defineAsyncComponent for better performance and lazy loading
const ComponentA = defineAsyncComponent(() => import('./ComponentA.vue'));
const ComponentB = defineAsyncComponent(() => import('./ComponentB.vue'));
const activeComponent = ref('ComponentA'); // Initial active component
</script>