VueJs — Unwrap slots content using the <template> tag

Photo by Samuel Zeller on Unsplash

When you use slots within your components, is common to end up with a couple of extra elements wrapping your content, but there is an easy way to remove them from your rendered view.

General note:
I’m assuming you have a basic knowledge of the VueJs Template Syntax and Named Slots.

Let’s say you have a message-box component with two named slots (“header” and “body”):

// message-box component
<template>
<div class="panel">
<div class="header">
<p><slot name="title"></slot></p>
</div>
<div class="body">
<slot name="body"></slot>
</div>
</div>
</template>

Now, when you use this component inside another:

<template>
<message-box>
<div slot="title">Some title</div>

<div slot="body">Some content</div>
    </message-box>
</template>

This component will be rendered as follows:

<template>
<div class="panel">
<div class="header">
<p><div>Some title</div></p>
</div>
<div class="body">
<div>
<div class="body"><div>Some content</div></div>
</div>
</div>
</div>
</template>

This works fine, but you actually don’t need those extra <div> around the content of each slot:

<p><div>Some title</div></p>

You can easily remove those<div> wrappers by using the reserved <template> tag

<template>
<message-box>
<template slot="title">Some title</template>

<template slot="body">Some content</template>
    </message-box>
</template>

And the rendered result would be something like this:

<template>
<div class="panel">
<div class="header">
<p>Some title</p>
</div>
<div class="body">
<div class="body">Some content</div>
</div>
</div>
</template>

Like what you read? Give Jeff a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.