Back
VueMediumNew
What are dynamic components and how do you switch between them?
<component :is="...">
Ideal Answer
The built-in <component> element with a dynamic :is binding lets you render different components in the same spot based on state, commonly used for tabbed interfaces.
JavaScript
<script setup>
import { ref } from 'vue'
import TabHome from './TabHome.vue'
import TabPosts from './TabPosts.vue'
const tabs = { home: TabHome, posts: TabPosts }
const currentTab = ref('home')
</script>
<template>
<component :is="tabs[currentTab]" />
</template>
Wrap it in <KeepAlive> if you want to preserve the state of inactive tab components instead of destroying/recreating them on each switch.