DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Cover image for Reusable components with scoped slots in vue
Alejandro Sierra
Alejandro Sierra

Posted on

Reusable components with scoped slots in vue

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.

Slots β€” Vue.js
cover image

Top comments (0)

Let's Get Wacky


Use any Linode offering to create something unique or silly in the DEV x Linode Hackathon 2022 and win the Wacky Wildcard category

β†’ Join the Hackathon <-