JAVASCRIPT

Render Dynamic Components in Vue 3

Learn how to dynamically render different components based on data in Vue 3 using the <component :is="..."> element for flexible UI construction.

// src/components/HomeComponent.vue
<template>
  <div>Welcome to the Home page!</div>
</template>
<script setup></script>

// src/components/AboutComponent.vue
<template>
  <div>This is the About page.</div>
</template>
<script setup></script>

// src/App.vue
<template>
  <nav>
    <button @click="currentTab = 'HomeComponent'">Home</button>
    <button @click="currentTab = 'AboutComponent'">About</button>
  </nav>
  <component :is="currentTab" />
</template>

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

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

<style scoped>
nav button {
  margin-right: 10px;
  padding: 8px 15px;
  cursor: pointer;
}
</style>
How it works: This snippet demonstrates how to render components dynamically in Vue 3 using the `<component :is="...">` special element. By binding the `is` attribute to a reactive variable that holds the name or imported component reference, you can switch the rendered component at runtime. This pattern is incredibly useful for building tabbed interfaces, wizards, or dashboards where different views need to be swapped based on user interaction or data.

Need help integrating this into your project?

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

Hire DigitalCodeLabs