Introduction to Vue.js Slots

/ #Vue.js


With Slots you can make it possible to structure the content of a component in a semantic way, and the parent component can control the contents of them.

A normal component

In a normal component with a prop you do something like this:

Vue.component('alert-box', {
  props: ['content'],
  template: '<div class="alert">{{ content }}</div>'
})

<alert-box content="The alert message"></alert-box>

Basic slots

The easiest way to use a slot is to just add <slot></slot> to your component like this:

Vue.component('alert-box', {
  template: '<div class="alert"><slot></slot></div>'
})

<alert-box>The alert message</alert-box>

Using slots like this is quite easy, but it does not make much sense what content can be added to <slot></slot> or what it does. When you add a simple slot like this all of the HTML you put inside your component will be passed through and put inside the slot. Vue.js also have a solution called name slots which we'll cover in the next section.

Named slots

Named slots makes it easy to assign parts of a slot to a specific part of your component. When you add a name to the slot it makes sense what the content of that should be. Look at this example:

Vue.component('alert-box', {
  template: '<div class="alert"><slot name="title"></slot><slot name="content"></slot></div>'
})

<alert-box><strong slot="title">The title</strong><p slot="content">The alert message</p></alert-box>

Here you will see that we create a slot called title and a slot called content. This way it make sense what content should be put in which slot and the template layout of the component looks nice and understandable for other developers.

You should try to create a few components and set them up with a couple of slots and in different ways. Once you get the hang of how to use them I'm sure you'll find them super helpful.

Comments

No comments yet...

Add comment

Newsletter

Subscribe to my weekly newsletter. One time per week I will send you a short summary of the tutorials I have posted in the past week.