How to create dynamic components in Vue

Creating dynamic components allows you to switch between different components at runtime based on data or user interactions, essential for building flexible UIs like tabs, modals, or dashboards. As the creator of CoreUI, a widely used open-source UI library, I’ve implemented dynamic component patterns in countless Vue applications over 25 years of development. From my expertise, the most effective approach is using the built-in <component> element with the is attribute to dynamically render different components. This provides clean, declarative component switching with full Vue reactivity.

Use the <component> element with is attribute to dynamically render components.

<template>
  <component :is="currentComponent" :data="componentData" />
  <button @click="switchComponent">Switch Component</button>
</template>

<script>
export default {
  data() {
    return {
      currentComponent: 'UserProfile',
      componentData: { name: 'John' }
    }
  },
  methods: {
    switchComponent() {
      this.currentComponent = this.currentComponent === 'UserProfile' ? 'UserSettings' : 'UserProfile'
    }
  }
}
</script>

Here the <component> element renders different components based on the currentComponent data property. Vue automatically destroys the previous component and creates the new one when the value changes. You can pass props normally, and the dynamic component receives them just like any regular component.

Best Practice Note:

This is the same dynamic component pattern we use in CoreUI Vue components for flexible layouts and conditional rendering. Consider using <keep-alive> wrapper around dynamic components to preserve component state when switching, and always ensure your dynamic component names are properly registered or imported.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author