Dynamic Components
Table of Contents
Dynamic components constitute the ability to dynamically change (i.e. switch) between components by binding an is attribute to the reserved <component> element.
We'll go through an example to best understand how dynamic components work. Assume we have separate components titled Home, Feed, and History that simply display text dictating what component it is.
When to Use
- Use this when you need to render different components based on user interaction (e.g., tabs, views)
- This is helpful as an alternative to multiple
v-if/v-elseblocks for conditional component rendering
Instructions
- Bind the
isattribute on<component>to a reactive value referencing the component definition - Use a
tabsobject mapping names to imported component definitions - Wrap
<component>with<KeepAlive>to preserve state when switching between dynamic components
Details
<!-- Home -->
<template><div class="tab">Home component</div></template>
<!-- Feed -->
<template><div class="tab">Feed component</div></template>
<!-- History -->
<template><div class="tab">History component</div></template>
Our goal is to build an interface that surfaces a list of tabs that can be clicked. Depending on what tab is clicked, we want to dynamically render a certain component.
When clicking between the tabs, we want components to be dynamically unmounted and mounted without the use of routing. Though something like this could be achieved by conditionally rendering child templates with the help of directives like