In this episode, we dive into how to handle repeatable but slightly different components in Vue.js, focusing on making your code cleaner and more manageable. We walk through a practical example with a notifications feed: imagine getting different types of notifications from your API (like 'post replied' or 'post upvoted') and wanting to render each a little differently in your UI without ending up with a spaghetti mess of v-if
statements everywhere.
We start off by building a common wrapper component for notifications and learn how to use Vue's slot
feature to inject custom content for each type. But pretty quickly, we see that using a pile of v-if
s for each notification type isn't scalable.
The solution? Dynamic components! We create a folder of individual notification types as separate Vue components (e.g., AppNotificationPostReplied.vue
and AppNotificationPostUpvoted.vue
). Then, we use Vue's <component :is="...">
syntax to render the correct component automatically based on the notification type from your API. This means you don't need extra if
statements just to show the right notification message — you just create a new component, import it, and map it to your notification type.
We also look at how to cleanly map API data (which might use snake-case or hyphens) to your component names, so you don't have to mess around with changing your API's structure. By the end of the episode, adding new notification types is a breeze: just build the component, drop it in, and everything works like magic. This pattern is super handy for notifications but could be reused for lots of similar cases in Vue. Give it a try and see how much tidier your components can be!