Introducing slot and scoped slots in Vue.js

Tram Ho

Surely in the process of working with Vue.js, you will encounter cases where you want to insert HTML content into child components in the same way as we still write normal HTML instead of using prop. Eg:

To do this, Vue.js provides <slot> </slot> so that we can insert content from the parent component into child components.

Some commonly used slots are:

  • Common components (Button, Modal, Card, Dropdown, Tabs, …)
  • Common shared layout components (Header, Navbar, Footer …)
  • Recursive components (Tree, Menu …)

Types of slots

Basic

Learn how to use the basics of slots. We have child child components using the slot as follows:

The parent component inserts the content inside child

The content after rendering is as follows:

Fallback content

All content inside <slot> </slot> will be used as fallback content when the parent component does not insert anything into the child component. For example:

The parent component calls the child but does not insert the content:

The resulting render will show the fallback content:

Name the Slot

The slot has a special attribute called name which allows us to name the slot. Within a component, there can be many slots with different names and Vue.js also allows an unnamed slot to contain content that does not match any slot name in the component. Let’s take a look at an example to make it easier to understand.

We have an componet card with 3 headers, content, footer. We will put into 3 slots as follows:

The parent component uses and transmits the content:

Results after rendering:

Scoped slots

Scoped slots are a special type of slot that allows you to transfer data from the child component to the parent component by assigning data via properties (it is similar to putting data into a component’s props). Let’s take a look at an example:

I have a child as follows:

As you can see, I passed into the slot an attribute that is the type of prop you usually see when passing into a component.

Next comes the parent component. We will retrieve the content from the text via the slot-scope property.

The data types that can be used in scoped slots can be string, number, object, array even you can pass methods.

summary

  • Slot and Scoped slot are one of the most powerful features of Vuejs. It allows us the ability to customize components with less coding, reusable code, help clean code and avoid DRY violations. Thank you for watching!
  • Reference: Home page
Share the news now

Source : Viblo