What is a slot in VueJS? Give me a slot, mom …

Tram Ho

Exactly like the title I mentioned. Slot literally means “Place” always.

  • Give me a place in my Vue component
  • ok son

Slot is a reservation

Slot in vue is a form of “booking” in the component, later when used, we can put other content into the reserved position. Vue allows us to book as many seats, as many as we want, a conditional home =)))) Each of these places is called a “slot”. Let’s see the following example. with mom for friendly 😄 )

So you changed the component I was born with 2 places that I reserved for you the image and name

Slot name

As the example above, we see that when the slot has a name, and pass the name to the slot, only the slot with that name will be changed, the rest will remain intact. If the slot has no name, all the information will be transferred. into the slot

Slot scope

To transfer data from mother to child, we bind the data we want to pass through slot <slot: name = “du-lieu” />

An example to see the benefits of slot in practice.

When I first received the design from the design side, the modal popup was extremely simple, including only the title, description and the three buttons below. At first glance, we only need 3 prop and an event to fire when clicking the button to change depending on the use case.

But after a while, the design team drew a new bunch, embedded the form, inserted another component into it, yes. Prop does not meet the crazy level of you design. And the way we refactor the modal by slot

By using the slot you will have components with the ability to cook it again and again. Hopefully with this tip, everyone will master the component more flexibly (y).

Share the news now

Source : Viblo