Vue Dynamic Components

🔄 Vue Dynamic Components

In Vue.js, dynamic components let you switch between multiple components at runtime using a single placeholder.

They’re perfect for tabs, dashboards, modals, and step-based UIs.


 What are Dynamic Components?

Instead of hardcoding a component name, Vue lets you render different components dynamically using the built-in <component> element and the :is attribute.

<component :is="currentComponent" />
  • currentComponent can be a component name, imported component, or async component.


 Basic Example: Switch Components

Parent Component


 

✔ Clicking buttons swaps components instantly.


 Using Component References (Recommended)

<component :is="currentComponent" />
data() {
return {
currentComponent: Home
}
}

✔ Safer than string names
✔ Better IDE support


 Dynamic Components with Tabs (Real-World)


 

✔ Clean and scalable tab system.


 Preserving State with <keep-alive>

By default, switching components destroys the old one.
Use <keep-alive> to cache components.

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

✔ Keeps form input, scroll position, and state
✔ Ideal for tabs & multi-step forms


 Conditional Dynamic Components

<component :is="isAdmin ? AdminPanel : UserPanel" />

 Dynamic Components with Props

<component :is="current" :user="user" />

✔ Props pass normally
✔ Events can be emitted normally ($emit)


 Dynamic Components + v-for

<component
v-for="item in items"
:key="item.id"
:is="item.component"
/>

✔ Used in dashboards & widget systems


 Async Dynamic Components (Performance ⚡)

Load components only when needed.

const Settings = () => import('./Settings.vue')
<component :is="Settings" />

✔ Smaller bundle size
✔ Faster initial load


 Common Use Cases

  • Tab navigation

  • Dashboards

  • Multi-step forms

  • Wizards

  • Modals

  • CMS page builders


 Common Mistakes ❌

❌ Using string names without registering components
❌ Forgetting keep-alive when state should persist
❌ Overusing dynamic components where simple v-if is enough


 Best Practices ✅

✔ Prefer component references over strings
✔ Use <keep-alive> wisely
✔ Combine with async imports for performance
✔ Keep dynamic logic simple and clear


Summary Table

Feature How
Dynamic render <component :is="comp" />
Cache state <keep-alive>
Tabs Dynamic components
Lazy load () => import()
Pass props Normal props

🏁 Conclusion

Vue dynamic components give you powerful runtime flexibility without complex logic.
They are essential for building modern, scalable, and high-performance Vue applications.

You may also like...