Reusable components with scoped slots in vue
Alejandro Sierra
Posted on November 3, 2019
What are slots first of all?
If you are not familiar with slots in Vue I suggest looking at the slots documentation in short, slots in Vue are a way to pass markup into a component directly from the parent to child component
So, what’s a scoped slot?
Scoped slots allow us to take this one step further by allowing data in the child component to be used by the parent. In turn, allowing the content to be displayed differently
This can be helpful when creating a reusable component that shares functionality but needs different variations of UI.
Let's take a look at an example:
// photo-gallery component
<template>
<div>
<h1>{{title}}</h1>
<div class="photo-gallery">
<slot v-bind:items="photos"></slot>
</div>
</div>
</template>
imagine that this component is called photo-gallery
its job is to retrieve data from a photos API and store it in a piece of local data called photos
// template for photo-gallery...
</template>
<script>
export default {
data () {
return {
photos: [
.....
we set up the outline by defining all the things we want any instances of photo-gallery to share. Such as having a title and a gallery container with custom styling.
When we use this component we have access to its photos using the items
property that was defined in v-bind:items=“photos”
basically saying “pass the photos as items
“.
When you use this component now it looks like this
<photo-gallery>
<template v-slot="props">
<ul class="alt-gallery">
<li class="alt-photo" v-for"item in props.items"></li>
</ul>
</template>
</photo-gallery>
We are given access to the photos by using v-slot=“items”
then we loop over each photo or “item” and create a alt-photo
list item.
Using this approach we can create multiple instances of the photo-gallery and can even make components for each instance like gallery-list
and alt-gallery
while passing the photos array into them like this
<photo-gallery>
<template v-slot="props">
<gallery-list
:photos="props.items"
/>
</template>
</photo-gallery>
Takeaways:
Using scoped slots, we delegate common functionality and markup to the scoped component. Then on each instance, we can change the way our data is represented visually.
Posted on November 3, 2019
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.