DEV Community

Ibrahim
Ibrahim

Posted on

Switch Between Components Dynamicly in Vue

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>
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

That's it! With dynamic component, you can avoid multiple and messy v-if conditions and keep your code clean and organized.

Top comments (0)