JAVASCRIPT

Dynamically Render Vue 3 Components with the 'is' Attribute

Learn to switch between different Vue 3 components dynamically using the special `is` attribute, ideal for tabbed interfaces or conditional rendering.

// components/ComponentA.vue
<template>
  <div class="component-box-a">This is Component A</div>
</template>
<style scoped>
.component-box-a { padding: 20px; border: 2px solid blue; background-color: #e0f2fe; margin: 10px; }
</style>

// components/ComponentB.vue
<template>
  <div class="component-box-b">This is Component B</div>
</template>
<style scoped>
.component-box-b { padding: 20px; border: 2px solid green; background-color: #e8f5e9; margin: 10px; }
</style>

// App.vue (Parent component)
<template>
  <div>
    <h2>Dynamic Component Example</h2>
    <button @click="currentComponent = 'ComponentA'">Show A</button>
    <button @click="currentComponent = 'ComponentB'">Show B</button>
    <br>
    <Transition name="fade" mode="out-in">
      <component :is="currentComponent"></component>
    </Transition>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import ComponentA from './components/ComponentA.vue';
import ComponentB from './components/ComponentB.vue';
import { Transition } from 'vue'; // Explicit import for clarity

const currentComponent = ref('ComponentA');
</script>

<style>
/* Optional: Add some basic transition styles */
.fade-enter-active, .fade-leave-active {
  transition: opacity 0.5s ease;
}
.fade-enter-from, .fade-leave-to {
  opacity: 0;
}
</style>
How it works: This snippet demonstrates how to use Vue 3's special `is` attribute to dynamically render different components based on a reactive state. By binding `currentComponent` to `:is`, Vue will render the component whose name matches the string value of `currentComponent`. This pattern is highly useful for building tabbed interfaces, wizards, or any scenario where you need to switch between different views or components without re-rendering the entire page. The example also includes a `<Transition>` component for a smooth fade effect when switching components, enhancing user experience.

Need help integrating this into your project?

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

Hire DigitalCodeLabs