Use Slot Vue Js

Posted onby admin

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

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. To my knowledge, Vue does not provide a way to do this. However here are two approaches worth considering. Watching the Slot's DOM for Changes. Use a MutationObserver to detect when the DOM in the slot changes. This requires no communication between components. Simply set up the observer during the mounted callback of your component. The v-slot directive was introduced in Vue 2.6.0, offering an improved, alternative API to the still-supported slot and slot-scope attributes. The full rationale for introducing v-slot is described in this RFC. Slots are a powerful tool for creating reusable components in Vue.js, though they aren’t the simplest feature to understand. Let’s take a look at how to use slots and some examples of how they can be used in your Vue applications.

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

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.

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.

Use Slot Vuejs

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

Use slot vue json

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:

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

Use Slot Vue Jsp

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:

Use Slot Vue Json