← Back to all snippets
VUE

Dynamic Component Rendering with `<component :is>`

Learn to render components dynamically in Vue 3 using the special `<component :is="...">` element. This is perfect for building flexible UIs that swap components at runtime.

<template>
  <div>
    <button @click="currentTab = 'HomeComponent'">Home</button>
    <button @click="currentTab = 'AboutComponent'">About</button>
    <button @click="currentTab = 'ContactComponent'">Contact</button>

    <p>Current Tab: {{ currentTab }}</p>

    <keep-alive>
      <component :is="currentTab"></component>
    </keep-alive>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import HomeComponent from './HomeComponent.vue';
import AboutComponent from './AboutComponent.vue';
import ContactComponent from './ContactComponent.vue';

const currentTab = ref('HomeComponent');
</script>

<!-- HomeComponent.vue -->
<template>
  <div>
    <h2>Welcome Home!</h2>
    <p>This is the content for the home tab.</p>
  </div>
</template>

<!-- AboutComponent.vue -->
<template>
  <div>
    <h2>About Us</h2>
    <p>Learn more about our company.</p>
  </div>
</template>

<!-- ContactComponent.vue -->
<template>
  <div>
    <h2>Contact Us</h2>
    <p>Get in touch with us.</p>
  </div>
</template>
How it works: This snippet illustrates how to render components dynamically based on a reactive value using Vue 3's `<component :is="...">` element. By binding `:is` to a string representing the name of a registered component (or the component object itself), you can switch between different components on the fly. The `keep-alive` wrapper is used here to preserve the state of inactive dynamic components, preventing them from being re-rendered each time they are switched.

Need help integrating this into your project?

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

Hire DigitalCodeLabs