Sometimes you need to dynamically switch between multiple components in the exact same location.
A common example of this is a tabbed interface, where clicking a tab swaps out the content block.
Instead of writing complex v-if statements for every possible component, Vue provides Dynamic Components!
<component> TagVue offers a special built-in element called <component>.
It acts as a placeholder that can dynamically morph into any component you tell it to.
You control which component it renders by binding a variable to its special :is attribute.
<template> <!-- Swaps between components dynamically based on the currentTab variable --> <component :is="currentTab"></component> </template>
When you switch away from a dynamic component, Vue completely destroys it to save memory.
If the user typed text into an input field on the "Settings" tab, then switched to "Home", their text will be permanently lost.
When they switch back to "Settings", the component mounts entirely from scratch.
<KeepAlive> ComponentIf you want dynamic components to maintain their internal state, you must wrap them in the built-in <KeepAlive> tag.
<KeepAlive> forces Vue to cache the inactive components in memory rather than destroying them.
<!-- Inactive components will now retain their state and variables! --> <KeepAlive> <component :is="currentTab"></component> </KeepAlive>
This provides an incredibly fast, seamless user experience for tabbed data entry!
What specific attribute must be used on the <component> tag to tell Vue which component to render?
How do you prevent a dynamic component from losing its data state when the user switches to a different tab?