← Back to all snippets
JAVASCRIPT

Dynamically Render Components with `is` Attribute

Learn how to render different Vue 3 components dynamically at runtime using the built-in `<component :is="componentName">` attribute for flexible UI management.

// Components/WelcomeMessage.vue
<template>
  <p>Welcome to our application!</p>
</template>
<script setup></script>

// Components/GuestMessage.vue
<template>
  <p>Please log in to access all features.</p>
</template>
<script setup></script>

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

<script setup>
import { ref, markRaw } from 'vue';
import WelcomeMessage from './components/WelcomeMessage.vue';
import GuestMessage from './components/GuestMessage.vue';

const isUserLoggedIn = ref(true);
const currentComponent = ref(isUserLoggedIn.value ? markRaw(WelcomeMessage) : markRaw(GuestMessage));

function toggleComponent() {
  isUserLoggedIn.value = !isUserLoggedIn.value;
  currentComponent.value = isUserLoggedIn.value ? markRaw(WelcomeMessage) : markRaw(GuestMessage);
}
</script>
How it works: This snippet demonstrates using Vue 3's `<component :is="...">` element to dynamically switch between different components based on application state. The `markRaw` function is used to prevent the component instance from being made reactive, which is a common performance optimization when dealing with dynamic components or large objects that don't need deep reactivity.

Need help integrating this into your project?

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

Hire DigitalCodeLabs