What is Dynamic Component in Vue: Explanation and Example
dynamic component in Vue allows you to switch between different components on the fly by changing a component's name or reference dynamically. It uses the built-in <component :is="..."> tag to render the chosen component based on a variable.How It Works
Imagine you have several different tools, but you only want to use one at a time depending on the task. A dynamic component in Vue works like a toolbox where you pick which tool (component) to use by name. Instead of hardcoding one component in your template, Vue lets you decide which component to show by changing a value.
Vue uses the special <component> tag with the :is attribute. This attribute takes a string or component reference and tells Vue which component to render right there. When the value changes, Vue swaps the displayed component automatically without reloading the page.
This is helpful when you want to create flexible interfaces that can change parts of the UI based on user actions or data, like tabs, modals, or dynamic forms.
Example
This example shows how to switch between two simple components using a button. Clicking the button changes the displayed component dynamically.
<template>
<div>
<button @click="toggleComponent">Toggle Component</button>
<component :is="currentComponent" />
</div>
</template>
<script setup>
import { ref } from 'vue'
const ComponentA = {
template: '<p>This is Component A</p>'
}
const ComponentB = {
template: '<p>This is Component B</p>'
}
const currentComponent = ref(ComponentA)
function toggleComponent() {
currentComponent.value = currentComponent.value === ComponentA ? ComponentB : ComponentA
}
</script>When to Use
Use dynamic components when you want to display different components in the same place without reloading the page or writing repetitive code. This is common in:
- Tab interfaces where each tab shows a different component.
- Wizard forms that change steps dynamically.
- Modal dialogs that can show different content types.
- Dashboards that load widgets based on user preferences.
Dynamic components help keep your code clean and your UI flexible by reusing the same spot for different content.
Key Points
- Use the
<component :is="...">tag to render dynamic components. - The
:isattribute accepts a component name or object. - Changing the
:isvalue swaps the rendered component instantly. - Great for tabs, modals, and dynamic UI parts.
- Helps avoid repetitive code and improves flexibility.