Slot Example Vue

A component can be 100% responsible for generating its output, like in this case:

May 07, 2020 Next Up, Let’s review Named Slots in VueJS with the help of an example. We covered a lesson on slots in VueJS in the last section. Slots help us to take the defined content inside the HTML markup of the component and put them in wherever specified in the template. The problem is it only works for a single default slot. But what if we want to create more complex markup, where we are looking. In this tutorial, we will learn about how to use the slots in vue.js with the help of examples. Slots helps us to pass the data between opening and closing component tags. In vue.js props are used to pass the data to its child components, but it is hard to pass when we have a complex code. In such cases slots can be used.

or it can also let the parent component inject any kind of content into it, using slots.

This page assumes you've already read the Components Basics.Read that first if you are new to components. # Slot Content Vue implements a content distribution API inspired by the Web Components spec draft (opens new window), using the slot element to serve as distribution outlets for content.

What is a slot? It’s a space in your component output that is reserved, waiting to be filled.

You define a slot by putting <slot></slot> in a component template:

When using this component, any content added between the opening and closing tag will be added inside the slot placeholder:

If you put any content side the <slot></slot> tags, that serves as the default content in case nothing is passed in.

Slot-scope

A complicated component layout might require a better way to organize content, with multiple slots as well.

This is why Vue offers us named slots.

Named slots

With a named slot you can assign parts of a slot to a specific position in your component template layout, and you use a slot attribute to any tag, to assign content to that slot.

Anything outside any template tag is added to the main slot.

For convenience I use a page single file component in this example:

Here is how we can use it, providing the slots content, in a parent component:

There is a handy shorthand, #:

Note: Vue 2.6 deprecated the slot attribute in favor of v-slot, and requires it to be added to a template tag (while slot could be applied to any tag)

Scoped slots

In a slot, we can’t access the data contained in the child component from the parent.

Vue recognizes this use case and provides us a way to do so:

Slot Example Vueling

In the parent we can access the dog name we passed using:

slotProps is just a variable we used to access the props we passed. You can also avoid setting a variable just to hold the props you pass to the child component, by destructuring the object on the fly:


More vue tutorials:

Slot Example Vue Online