Vue custom layouts

#coding tips #vue tips

Updated January 26, 2024 | 2 min read

When building Vue.js applications, managing layouts efficiently can significantly enhance code organization and maintainability. In this article, we'll explore three approaches for implementing custom layouts in Vue 3 and discuss their pros and cons.

Basic Slot-Based Layouts

The first approach involves creating layout components with slots for dynamic content insertion.

Implementation:

<!-- layouts/DashboardLayout.vue -->
<template>
  <div>
    <MainNav />
    <SideNav />
    <main>
      <slot></slot>
    </main>
  </div>
</template>

<script>
import MainNav from '@/components/MainNav.vue';
import SideNav from '@/components/SideNav.vue';

export default {
  components: {
    MainNav,
    SideNav,
  },
};
</script>

Usage:

<!-- views/HomeView.vue -->
<template>
  <DashboardLayout>
    <!-- Your home view content here -->
  </DashboardLayout>
</template>

Router-Based Layouts

The second approach utilizes router metadata to assign specific layouts to routes.

Implementation:

// index.js (Router Configuration)
const routes = [
  {
    path: '/',
    component: DefaultLayout,
    children: [
      {
        path: '/',
        name: 'Home',
        component: HomeView,
      },
    ],
  },
  // Define other routes...
];

Usage:

No changes required in component usage.

Dynamic Layout Selection

The third approach introduces a dynamic layout selector based on route metadata.

Implementation:

<!-- layouts/TheAppLayout.vue -->
<template>
  <component :is="layout">
    <router-view />
  </component>
</template>

<script setup lang="ts">
import { computed } from 'vue';
import { useRoute } from 'vue-router';

const route = useRoute();
const layout = computed(() => {
  const layout = route?.meta?.layout;
  return layout ? `The${layout}Layout` : 'div';
});
</script>

Usage:

<!-- src/App.vue -->
<template>
  <div id="app">
    <TheAppLayout />
  </div>
</template>

Conclusion

Each approach offers its own advantages:

  • Slot-Based Layouts: Simple and direct, suitable for smaller applications or when layout customization is minimal.
  • Router-Based Layouts: Provides better organization and scalability, particularly for applications with multiple layouts and complex routing requirements.
  • Dynamic Layout Selection: Offers maximum flexibility by dynamically selecting layouts based on route metadata. Ideal for large-scale applications with varying layout needs.

Choose the approach that best fits your project requirements and scale. For simpler applications, Approach 1 might suffice, while larger projects may benefit from the more structured Approach 2 or the dynamic capabilities of Approach 3.

By implementing custom layouts effectively, you can enhance code maintainability and improve the overall user experience of your Vue.js applications.