What Is a Dynamic Component in Vue?

In Vue, dynamic components let you switch or load a component programmatically, deciding at runtime which component is displayed.
There are several ways to use dynamic components in Vue. Here are some of them:
- The <component> element: Vue has a built-in <component> element. Its is prop decides which component is displayed:
VueCode fragment <template> <component :is="currentComponent"></component> </template> <script> export default { data() { return { currentComponent: 'MyComponent', }; }, }; </script>Here the currentComponent data property decides which component is shown; your application logic can change it at any time.
- With <keep-alive>: Vue's <keep-alive> element keeps dynamic components in memory and reuses them — useful when a component's state should be preserved while switching:
VueCode fragment <template> <keep-alive> <component :is="currentComponent"></component> </keep-alive> </template> - With v-if or v-show: the decision to show a component can also be made with the v-if or v-show directives, adding or removing components under certain conditions:
VueCode fragment <template> <div> <my-component v-if="shouldShowComponent"></my-component> </div> </template> <script> export default { data() { return { shouldShowComponent: true, }; }, }; </script>
These are only a few ways of using dynamic components in Vue; which one to choose depends on the needs and structure of your application.
Have a question about this article? Write to me


