Magic of vue template-slots

ManiKanta Koppala
Vue.js Developers
Published in
3 min readFeb 9, 2020

Have you ever faced a situation where you want to change the layout of the screen dynamically, keeping the same components?

Mostly components stay the same but few changes in the layout

In a nutshell, all the components remain the same, but the design of the page changes on run time. For this, vue template-slots are the best companions.

How it works

Vue template slots allow us to give some space in our component to inject data when someone is using that component. We will define component(say navigation) like this,

<a
v-bind:href="url"
class="nav-link"
>
<slot></slot>
</a>

Now when we are using this component, we can replace the slot with the content we want.

<navigation-link url="/profile">   
Your Profile.... <!--Will be added in place of slot-->
</navigation-link>

What if we want to keep multiple data in multiple places? For that, we have named slots.

<div class="container">
<header>
<!-- We want header content here -->
<slot name="header"></slot>
</header>
<main>
<!-- We want main content here -->
<slot name="content"></slot>
</main>
<footer>
<!-- We want footer content here -->
<slot name="footer"></slot>
</footer>
</div>

Now when we are using this component, we can replace specific slots by,

<base-layout>  <template v-slot:header>
<h1>Here might be a page title</h1>
</template>
<template v-slot:content>
<p>A paragraph for the main content.</p>
<p>And another one.</p>
</template>
<template v-slot:footer>
<p>Here's some contact info</p>
</template>
</base-layout>

(NOTE: Please refer to this documentation for a complete understanding of vue template slots)

With a pretty good understanding of these concepts, let’s see how we can build our pages to change the template dynamically. For this, let’s start with a simple example,

where there are two section user details and user activity log. Each section can have a lot of components. Now instead of rendering them directly in a single file, let’s break into two things.

Index.vue has all the components, whereas the template.vue has slots to place the components and styles. Let’s see how our code looks like,

index.vue(list of components)
template.vue (all the designs goes here)

As you know, we are loading my-template(layout) in the index.vue dynamically based on some condition, and we are telling to replace the slots with the components we are giving, and in the layout, we provided slots to place those components.

(Note: This is one of the articles written in a series of vue plugin-based development. If you are interested, please check out the whole story)

--

--