Component Variations with the Base Component Pattern

The Base Component pattern is one of my favourite ways to make many different versions and variants from a single component.

It has a few basic steps:

  1. Create your base component
  2. Wrap it with another component to get a variant of the original
  3. Repeat step 2 as many times as you need

Here's an example, creating a DisabledButton variant out of a BaseButton component:

<!-- DisabledButton.vue -->
<template>
<!-- Never forget how to create this disabled button.
Package it up using the Base Component pattern. -->
<BaseButton
type="disabled"
disabled
>
<!-- You can't accidentally use the wrong icon now.
It's provided here for you -->
<template #icon>
<Icon type="disabled" />
</template>
</BaseButton>
</template>

You can use this pattern in many different ways:

  • Lock down props — take a Button component and hard code a few props to get a DisabledButton. Now you can just use the DisabledButton directly without fiddling with all the necessary props each time.
  • Lock down slots — create an InfoButton variant where the icon passed to the Button is always the same. So now, if you ever need to change the icon (or anything else), you can do it in one place.
  • Simplify props — sometimes components end up with dozens of props, primarily for edge cases. Instead, create a BaseButton with all the props, and a Button that passes on only the most common ones. This is a lot safer and easier to use, and the documentation for this component is easier to read.

I've included more on this pattern in Reusable Components.