JAVASCRIPT

Vue 3 Dynamic Component Loading with `is` Attribute

Dynamically render different Vue 3 components based on runtime conditions or user interaction using the `<component :is="componentName">` attribute.

// components/ComponentA.vue
<template>
  <div class="component-a">
    <h3>Component A</h3>
    <p>This is the content for Component A.</p>
  </div>
</template>
<style scoped>.component-a { border: 1px solid blue; padding: 10px; }</style>

// components/ComponentB.vue
<template>
  <div class="component-b">
    <h3>Component B</h3>
    <p>This is the content for Component B.</p>
  </div>
</template>
<style scoped>.component-b { border: 1px solid green; padding: 10px; }</style>

// App.vue
<template>
  <div>
    <h2>Dynamic Component Example</h2>
    <button @click="toggleComponent">Toggle Component</button>
    <hr>
    <component :is="currentComponent"></component>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue';
import ComponentA from './components/ComponentA.vue';
import ComponentB from './components/ComponentB.vue';

const showA = ref(true);

const currentComponent = computed(() => (showA.value ? ComponentA : ComponentB));

function toggleComponent() {
  showA.value = !showA.value;
}
</script>
How it works: This snippet demonstrates how to dynamically render different components in Vue 3 using the `<component :is="...">` special element. By binding the `is` attribute to a reactive variable (in this case, `currentComponent` computed property), you can switch between `ComponentA` and `ComponentB` at runtime. This is extremely useful for building flexible UIs like tabbed interfaces, wizards, or content management systems where the rendered component depends on the application's state.

Need help integrating this into your project?

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

Hire DigitalCodeLabs