Create reusable Vue components — using slots

Sachin Gadhari
2 min readJan 4, 2021

In this blog, we will see what is meant by slots, how powerful slots are, and how we can create reusable components using slots.

According to the MDN web documentations, the slot element is part of the Web Components technology suite. It is a placeholder inside a web component that you can fill with your own markup, which lets you create separate DOM trees and present them together.

Similarly, Vue implements the <slot> element to serve the dynamic contents inside the component which makes our component more generic.

For a better understanding of the concept let see a simple example.

Let's imagine we want to create a button component and where we want to display button names and the icons to its left or right depending on our use case.

If we implement the ButtonComponent to fulfill the above use case using props, then we need to maintain a lot of props like buttonText, leftIconColor, rightIconColor, showLeftIcon, showRightIcon, and the list goes on.

This approach doesn't scale very well for the more complex component as we will end up using more and more props which will result in the state explosion problem and will decrease the maintainability of the component.

A better solution to this is a slot that makes our component more generic and versatile. Instead of maintaining too many props on our component, we can make use of slots as shown in the below snippet.

//AppButtonComponent<template>
<button>
<slot></slot>
</button>
</template>

Now we can use our button component in a very flexible way and can control all the HTML content which we want to render according to our need from the parent component. We can now easily move the icon before and after the text or can add some custom styling.

// AppComponent<template>
<AppButton>
<Icon />
Press Me
</AppButton>
</template>
<script>
import AppButton from "./components/AppButton";
import Icon from "./components/Icon";
export default{
components: {
AppButton,
Icon
}
}
</script>

In the above example for simplicity, we are just rendering the HTML which is being passed from the parent component in our case from AppComponent. But we can do even more things with slots like we can add v-on=’$listeners’ to out button component so that we can register all possible event listeners like v-on:click or v-on:chnage on our AppButton component inside our AppComponent.

This is how we can design better and reusable Vue components using slots. Slots are a very powerful tool and it gives more flexibility to our component.

For more information on slots and their different types like named slots, scoped slots, and many others, please check out the official documentation of Vue.

Thank you for reading! 😃

--

--