When crafting components with Vue.js you can go multiple ways. You can go with the props based approach or you can choose the slot based solution.
If you’re using props, things can quickly get out of hand, especially when you are dealing with a lot of variables and custom options. To illustrate this I have created 2 versions of a
CustomButton component. One is using props, the other one is using slots.
Here is what the
CustomButtonWithProps component looks like:
As you see, you have a bunch of options customizing the component via
props . For example, you can show an icon in front of the text, after the text, change the button-text and color.
Here is how I use this component(in this example we’re using it directly in
As you can see, we have a tightly wrapped component in
App.vue . And this is pretty much all the upside the props approach has.
CustomButtonWithProps component itself, it is starting to get messy. We have a fairly large component that is actually kinda bulky. We just can say we want to show the icons are not. But we can’t change the icon itself without rewriting the component. Same goes with the color. We can change the color, but we can’t change the font-size, font-decoration etc.
That is where we take a look at the slot approach of writing a component in Vue.js. As you will see, this way we can create a much more flexible component.
Here is the
Here you can see that the component is much cleaner than the
CustomButtonWithProps component. This is because we don’t have to pass props to it. Every variable thing we render we set in our parent-component. In this case our
I’m gonna start with the downside of implementing
CustomButtonWithSlots this way:
Your parent-component gets a little more bloated. But that's about it. From there we only have upsides.
- We are much more flexible with this approach: We can set whatever icon we want in both slots, we don’t have to predefine any icons in our
CustomButtonWithSlotscomponent. Which makes the component much more reusable.
- We even can pass other components to our
CustomButtonWithSlotscomponent. Let’s say we have an Image/Icon-component we want to use instead of the FontAwesome icons above. Then we simply pass the component in the icon-slot.
- You don’t have to deal with if-else clauses inside the
CustomButtonWithSlotscomponent. You either pass the data or not. No need to check whether it’s there or not.
- Last but not least: Your component itself is much more readable and less confusing.
Keep in mind that this is a pretty small example. But as bigger your components get, the more confusing they are going to get to other people.
I’m not saying that props never make sense, they're here for a reason. But for larger and more flexible components please consider using slots over props.
If you write your components with slots, you give yourself and your team members much more flexibility and code that is easier to read.