JAVASCRIPT

Dynamically Render Vue 3 Components

Learn how to use Vue 3's 'is' attribute to dynamically switch between multiple components based on a reactive state, enhancing UI flexibility.

<template>
  <div>
    <button @click="activeComponent = 'ComponentA'">Show A</button>
    <button @click="activeComponent = 'ComponentB'">Show B</button>

    <KeepAlive>
      <component :is="activeComponent"></component>
    </KeepAlive>
  </div>
</template>

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

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

<!-- ComponentA.vue -->
<template>
  <div style="border: 1px solid blue; padding: 10px; margin-top: 10px;">
    <h3>Component A</h3>
    <input type="text" placeholder="Type something in A">
  </div>
</template>

<!-- ComponentB.vue -->
<template>
  <div style="border: 1px solid green; padding: 10px; margin-top: 10px;">
    <h3>Component B</h3>
    <p>This is component B content.</p>
  </div>
</template>
How it works: This snippet demonstrates how to dynamically render different Vue 3 components using the special `<component :is="...">` element. The `activeComponent` ref determines which component is currently displayed. We also use `<KeepAlive>` to preserve the state of inactive components (like the input field in ComponentA) when switching, which is often desired in dynamic component scenarios, preventing re-renders and maintaining user input.

Need help integrating this into your project?

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

Hire DigitalCodeLabs