To have multiple layouts depending on the page in your Vue.js application using Inertia.js, you can modify your app.js file and create separate layout components for each layout you want to use.
Here's an example of how you can achieve this:
- Create a new layout component for the forum layout. Let's call it
ForumLayout.vue. This component will contain the sidebar and any other specific layout elements for the forum pages.
<template>
<div>
<!-- Sidebar content -->
<sidebar></sidebar>
<!-- Main content -->
<slot></slot>
</div>
</template>
<script>
export default {
components: {
Sidebar: () => import('./Sidebar.vue'),
},
};
</script>
- Modify your
app.jsfile to dynamically resolve the layout based on the page. You can update theresolvefunction to check for specific page names and assign the appropriate layout component.
import { createApp, h } from 'vue';
import { createInertiaApp, Link, Head } from '@inertiajs/inertia-vue3';
import { resolvePageComponent } from 'laravel-vite-plugin/inertia-helpers';
import { InertiaProgress } from '@inertiajs/progress';
import { ZiggyVue } from 'ziggy';
import DefaultLayout from './Shared/Layout.vue';
import ForumLayout from './Shared/ForumLayout.vue';
createInertiaApp({
resolve: async (name) => {
let layout = DefaultLayout;
if (name === 'Forum') {
layout = ForumLayout;
}
const page = await resolvePageComponent(`./Pages/${name}.vue`, import.meta.glob('./Pages/**/*.vue'));
page.default.layout ??= layout;
return page;
},
setup({ el, App, props, plugin }) {
createApp({ render: () => h(App, props) })
.component('Link', Link)
.component('Head', Head)
.use(ZiggyVue)
.use(plugin)
.mount(el);
},
title: (title) => `KE - ${title}`,
});
InertiaProgress.init({
color: 'blue',
showSpinner: true,
});
- Update your
Home.vuecomponent to use the default layout or the forum layout if needed.
<script setup>
</script>
<template>
<default-layout>
<h1>Hello world</h1>
</default-layout>
</template>
With this setup, the DefaultLayout component will be used for all pages except for the Forum page, which will use the ForumLayout component. You can create additional layout components and update the resolve function accordingly to handle more layouts.
Note: Make sure to import the necessary layout components in your app.js file.
Remember to compile your assets after making these changes.