JAVASCRIPT
Dynamically Rendering Components with Vue 3's <component :is> Attribute
Learn to switch between different components at runtime in Vue 3 using the `<component :is>` attribute, perfect for tabbed interfaces or dynamic forms.
// ComponentA.vue
<template><div>Component A Content</div></template>
<script>export default { name: 'ComponentA' };</script>
// ComponentB.vue
<template><div>Component B Content</div></template>
<script>export default { name: 'ComponentB' };</script>
// App.vue
<template>
<div>
<h1>Dynamic Component Example</h1>
<button @click="currentComp = 'ComponentA'">Show A</button>
<button @click="currentComp = 'ComponentB'">Show B</button>
<hr />
<!-- The component displayed changes based on currentComp's value -->
<component :is="currentComp"></component>
</div>
</template>
<script>
import { ref } from 'vue';
import ComponentA from './ComponentA.vue';
import ComponentB from './ComponentB.vue';
export default {
components: {
ComponentA,
ComponentB
},
setup() {
const currentComp = ref('ComponentA'); // Default component to show
return {
currentComp
};
}
};
</script>
How it works: This snippet demonstrates Vue 3's powerful `<component :is>` attribute, which allows you to dynamically render different components based on a reactive value. In `App.vue`, `currentComp` is a `ref` that holds the name of the component to be rendered. By binding this `ref` to `:is`, Vue automatically swaps `ComponentA` or `ComponentB` in and out of the DOM as `currentComp` changes. This pattern is incredibly useful for building dynamic interfaces like tabbed navigation, wizard forms, or dashboards where content needs to switch seamlessly without full page reloads. Vue handles the component instance management, including mounting and unmounting, efficiently.