While building most apps we need to have different layouts depending on the route. For example we might have a different base layout for someone logging in (/login
) and for someone visiting a dashboard (/dashboard
). Let’s go over one of the easy ways to accomplish this with Vue router.
First we need to define the two layouts.
Example Public.vue layout
<template>
<router-view></router-view>
</template>
<script>
export default {
name: 'PublicLayout',
};
</script>
<style>
</style>
Notice the only template structure we define for the public layout is a <router-view>
. Each of your layouts will need the <router-view>
that tells Vue to put the contents of the route in there.
Example App.vue layout
<template>
<div>
<nav>
<ul>
<li><router-link to="/dashboard">Dashboard</router-link></li>
<li><router-link to="/logout">Logout</router-link></li>
</ul>
</nav>
<div>
<router-view></router-view>
</div>
</div>
</template>
<script>
export default {
name: 'AppLayout',
};
</script>
<style>
</style>
Again notice this layout also has a <router-view>
.
Any route that uses this layout will include the nav. We can add in other things like a sidebar, footer, and more, but for demonstration purposes it’s easier to show the concept with less.
Next is the route file. Let’s say we have a couple routes a /login
and a /dashboard
. /login
should have the public layout and /dashboard
should have the app layout.
Example route file.
import Vue from 'vue';
import Router from 'vue-router';
import AppLayout from '@/layouts/App.vue';
import PublicLayout from '@/layouts/Public.vue';
import Dashboard from "@/views/Dashboard.vue";
Vue.use(Router);
export default new Router({
mode: 'history',
base: process.env.BASE_URL,
routes: [
{
path: '/login',
component: PublicLayout,
children: [
{
path: '',
component: Login,
},
],
},
{
path: '/dashboard',
component: AppLayout,
children: [
{
path: '',
component: Dashboard,
},
],
},
],
});
There are a couple key concepts. First notice the top level route defines the path. In our example that would be /login
or /dashboard
. Each of those top level routes define which layout they will use.
/login
uses the PublicLayout
because the user is not authenticated yet.
/dashboard
uses AppLayout
and assumes the user is authenticated.
Both /login
and /dashboard
have a children property on them and each have a path of ''
. This tells Vue to display that component for /login
and /dashboard
by default when that route is visited.
Below is a working example of the above code. If the sandbox doesn’t load properly use https://codesandbox.io/s/vue-layout-demo-mr0oh?fontsize=14.