The Power of Scoped Slots in Vue

Scoped slots opened a new way of using our Vue components dynamically. It can be useful when you need a flexible markup in a template, and also you need access to some data from your component.

Getting Started

Scoped slots were introduced in Vue 2.1.0, so it’s not a fresh thing right now. However, we experienced it’s a quite less known feature.

The whole idea behind scoped slots is to bring more flexibility to your components, by binding data to your slots what can be used by the markup what we use in the slot. Let’s see a basic example.

A Sample Component

The complexity of the component does not matter, you can use scoped slots whenever you need.

<template>
    <div>
        <h1>The Item:</h1>
        <slot v-bind="item">{{ item.name }}</slot>
    </div>
</template>

<script>
    export default {
        data() {
            return {
                item: { name: 'Item', price: 900 }
            };
        }
    }
</script>

Now as you see, we could bind the item to the slot. That means with a little trick; we can use the data from our slots. Also, we can define a default content of our slots like as basic slots.

<component>
    <template slot-scope="product">
        <strong>{{ product.name }}</strong>
    </template>
</component>

By using the template with the slot-scope attribute, we have access to the data what we have bound to the slot in our component. The parameter what we pass to the slot-scope has no importance; it just refers to the temporary variable name what we want to use. Now we can override the default slot content how we want.

Since 2.5.0+ the scoped slots are no longer limited to <template>. It can be used on any element or component.

In the documentation, you can see different ways and datatypes of bindings. Also, another big thing what brings the flexibility on a higher level is that we can use scoped slots in loops. You can fully customize your loop items easily.

Summary

Scoped slots brought a new way of flexibility to the framework. We suggest digging a bit deeper to understand how does this feature work fully and to recognize the possibilities what it offers.

Here you can find an example how it works: https://jsfiddle.net/rnkprw6m/

Leave a Reply

Your email address will not be published. Required fields are marked *