Vue Dynamic Components: Swap Components on the Fly
Use Vue's `<component :is="...">` element to render different components based on a state variable, like swapping views in a tabbed interface. The footgun: components are destroyed on switch; use `<KeepAlive>` to preserve their state and avoid losing user…
WHY IT EXISTS To dynamically render one of several possible components in a specific location without resorting to complex v-if/v-else-if/v-else chains. This simplifies logic when the choice of component depends on application state, making the template cleaner and the state easier to manage.
THE MENTAL MODEL Think of a single frame on a wall where you can swap out different pictures. The <component> element is the frame, and the :is attribute tells Vue which "picture" (which component) to display at any given moment. The picture can be changed based on a button press or any other state change.
HOW IT WORKS You use the special <component> element and bind its :is attribute to a variable in your component's state. This variable holds either the string name of a registered component (e.g., 'TabA') or the imported component object itself. When the variable's value changes, Vue automatically unmounts the old component and mounts the new one in its place.
WHEN TO USE IT Use dynamic components for building tabbed interfaces, multi-step wizards, or any UI where a section of the page needs to switch between different, self-contained views. It's much cleaner than a long v-if/v-else chain when you have three or more components to toggle between.
WHEN NOT TO USE IT For simple binary conditional rendering (showing or hiding a single component), a v-if is simpler and more direct. If the components are not interchangeable or do not share a common "slot" in the UI, this pattern does not apply. It's for swapping components in the same location.
ONE CANONICAL EXAMPLE A settings page with tabs for 'Profile', 'Billing', and 'Notifications'. A parent component holds a currentTab state variable. The template has <component :is="currentTabComponent"></component>. Buttons change currentTab from 'Profile' to 'Billing'. A computed property, currentTabComponent, maps the string to the actual imported ProfileComponent or BillingComponent object. By default, switching tabs destroys the old component's state (e.g., unsaved form data). To fix this, you wrap the dynamic component: <KeepAlive><component :is="..."></component></KeepAlive>.
Read the original → vuejs.org
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.