Slot concept in Vuejs

Tram Ho

1. What is Slots?

Slots is a Vue Components technique that allows you to place content in a new location or create generic components. What’s the best way to understand how Slots work? I will give the concept to apply it to the situations where you will see the visualization of the project.

Let me start with a simple example:

(first)

(2)

You can also leave a default content when you do not add anything between the opening / closing tags of the Button component

I fix a bit in the code:

(first)

(2)

2. Multiple / Named Slots

You can add multiple slots into a component. If you do this, you need to provide a name for each slot . If any slot has no name , it is the default slot . For example to create multiple slots .

3. Scoped Slot

One thing you need to know is that you can pass the data / function from the children component to the parent component . To demonstrate this, we will create a CurrentUser component:

Some note:

  • slotProps you can replace with a name you want.
  • If you are only using the default slot , you can remove the template tag and put the v-slot directive directly in the CurrentUser tag.
  • You can use Object Destructuring to make a reference directly to the data instead of using a variable name: v-slot="slotProps" => v-slot="{ user }" .
  • If the default slot you can write as: v-slot:default="slotProps" => v-slot="slotProps" .
  • v-slot can be abbreviated to # .
    • default slot: v-slot="slotProps" => #default="shotProps" .
    • named slot: v-slot:title="slotProps" => #title="shotProps" .

If you find this article useful to you when you first learn Vue, give me 1 vote [email protected] # $% ^ & *

Share the news now

Source : Viblo