Working with Dynamic Components in Vue.js
A pattern for cleaner conditional rendering
Overview
Dynamic components in Vue.js let you render different components conditionally based on application state. The article illustrates this concept through a commenting platform where logged-in and logged-out users see different interfaces.
The Core Syntax
The core syntax uses the :is attribute to reference a dynamic component:
<Component
:is="dynamicComponent"
v-bind="dynamicComponentProps"
/>The :is attribute points to the component to render, while v-bind passes props dynamically to that component.
A Practical Example
In a commenting platform, the application decides whether to load CommentBoxLoggedIn or CommentBoxLoggedOut based on user authentication status. These decisions are calculated as computed properties rather than embedded in templates — improving maintainability and scalability.
<template>
<Component :is="commentBox" v-bind="commentBoxProps" />
</template>
<script>
export default {
computed: {
commentBox() {
return this.user
? 'CommentBoxLoggedIn'
: 'CommentBoxLoggedOut';
},
commentBoxProps() {
return this.user
? { user: this.user, postId: this.postId }
: { postId: this.postId };
}
}
};
</script>Extended Use Cases
Dynamic components prove particularly valuable when handling nested functionality. For reply actions within comments, child components (like CommentItem) receive component names and properties as props, allowing them to render appropriate components with modified props like different parentId values.
Why It Matters
This approach offers several benefits: enhanced code organization, improved readability through separation of logic from templates, support for transitions between components, and greater structural manageability in complex applications.
When you start seeing repeated v-if / v-else blocks switching between similar components, dynamic components are usually the cleaner pattern.