Seamlessly Transitioning Between Desktop and Mobile layout in NuxtJS

G7vo...Hj1n
7 Aug 2023
39

I’ve been dabbling with NuxtJS as of late and it comes build in with a lot of features in this article will showcase how to seamlessly transition and build your app in desktop and mobile based on architectural pattern I find most practical.

Writting correct architecture benefits the project in the long run of being more flexible and following a certain pattern. In Vue/React most people would just focus on defining it in component section but that’s not optimal.
We will use pages directory as it’s main file-based routing and layouts that should be custom added. The layouts/ directory and will be automatically loaded via asynchronous import when used. More about it you can check here.

<template>
    <main class="login container-fluid p-4">
        <template v-if="isMobile">
        <MobileLoginLayout>
          <NuxtLayout name="mobile-login"></NuxtLayout>
        </MobileLoginLayout>
        </template>

      <template v-else>
        <DesktopLoginLayout>
          <NuxtLayout name="desktop-login"></NuxtLayout>
        </DesktopLoginLayout>
      </template>
    </main>
  </template>
  
  <script setup>

  import { isMobile } from 'mobile-device-detect';
  import MobileLoginLayout from '~/layouts/auth/mobile-login.vue'; 
  import DesktopLoginLayout from '~/layouts/auth/desktop-login.vue';
  
  definePageMeta({ layout: 'auth/login' });
  </script>v

The upper code is in pages/login.vue so basically /login endpoint. Used isMobile package you can find it here
Two <templates> are created with v-if and render the correct dimension based on device to /login page.
We as well import MobileLoginLayout and DesktopLoginLayout from layout directory where we define the views from both options. 
<NuxtLayout /> can be used to override default layout on app.vue, error.vue or even page components found in the /pages directory.
Finally you can define layouts/auth/mobile-login.vue and layouts/auth/desktop-login.vue as you please and your components directory will hold mainly functionality like API request, form upload etc. 

NuxtJS offers a plethora of powerful tools at its disposal, including middleware, composables, plugins, and more. 
By leveraging these features, developers can structure their applications in a more organized and scalable manner. 
Rather than relying solely on components for handling complex logic, it is recommended to distribute the logic across different parts of the application, where it makes sense.

Get fast shipping, movies & more with Amazon Prime

Start free trial

Enjoy this blog? Subscribe to Mozes721

1 Comment