JAVASCRIPT

Dynamic Components with Vue 3's `is` Attribute

Render different components dynamically based on data using Vue 3's special `is` attribute, ideal for tabbed interfaces or wizards.

// ComponentA.vue
<template>
  <div>
    <h3>Component A</h3>
    <p>This is the content for Component A.</p>
  </div>
</template>

// ComponentB.vue
<template>
  <div>
    <h3>Component B</h3>
    <p>This is the content for Component B.</p>
  </div>
</template>

// App.vue
<template>
  <div>
    <button @click="currentComponent = 'ComponentA'">Show A</button>
    <button @click="currentComponent = 'ComponentB'">Show B</button>

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

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

const currentComponent = ref(markRaw(ComponentA));

// Or, if using string names (requires global registration or explicit import and map)
// const currentComponent = ref('ComponentA');
// const components = {
//   ComponentA,
//   ComponentB
// };
// in template: <component :is="components[currentComponent]" />
</script>
How it works: This snippet demonstrates dynamic components in Vue 3 using the `<component>` tag with the `is` attribute. This allows you to switch between components dynamically based on data. The example shows how to import components and use a reactive reference to store the currently active component. The `keep-alive` wrapper is used to preserve the state of inactive dynamic components, preventing them from being unmounted and re-mounted every time you switch. `markRaw` is used for performance optimization when assigning components directly to a reactive ref, preventing Vue from trying to make the component object itself reactive.

Need help integrating this into your project?

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

Hire DigitalCodeLabs