There are times when we need to switch Vue components dynamically. For example, when displaying different content based on active tabs.
Instead of using multiple v-if
conditions like this:
<script setup> import { ref } from 'vue' import ProfileCard from './components/profile-card.vue' import SettingCard from './components/setting-card.vue' import HelpCard from './components/help-card.vue' const activeTab = ref('profile') </script> <template> <div> <profile-card v-if="activeTab === 'profile'" /> <setting-card v-else-if="activeTab === 'setting'" /> <help-card v-else /> </div> </template>
It's better to a use dynamic component instead, like this:
<script setup> import { ref } from 'vue' import ProfileCard from './components/profile-card.vue' import SettingCard from './components/setting-card.vue' import HelpCard from './components/help-card.vue' const activeTab = ref('profile') const tabs = { profile: ProfileCard, setting: SettingCard, help: HelpCard } </script> <template> <component :is="tabs[activeTab]" /> </template>
It's much easier to read and maintain.
With this method, we only need to store all tab components in the tabs
object without writing multiple v-if
conditions.
Explanation
<component />
is a built-in Vue component that can render a component dynamically based on the :is
attribute.
The :is
attribute can accept a .vue
component, the name of a global component (string), or an HTML tag.
Example:
<script setup> import MyComponent from './components/my-component.vue' </script> <template> <!-- Imported Component --> <component :is="MyComponent" /> <!-- Global Component --> <component is="GlobalComponent" /> <!-- HTML Tag --> <component is="h1">H1 Component</component> </template>
That's it! With dynamic component, you can avoid multiple and messy v-if
conditions and keep your code clean and organized.
Top comments (1)
This was such a well-written and thoughtful post—I really enjoyed the way you explained your ideas and offered a fresh perspective. Looking forward to reading more from you!