Using reactivity principles to dynamically switch UI layouts depending on a user's screen size and orientation.
This is a starter project that uses @vueuse/core
to create dynamic layouts based on the user’s screensize.
Create the various layouts
in the /layouts directory
. In our case, we have desktop.vue
that represents the desktop layout, tablet.vue
for tablet layout and mobile.vue
for mobile layout.
Use useMediaQuery
to identify various breakpoints. The returned breakpoint are valid ref<boolean>
that we can use to dynamicaly switch between the layout.
import { useMediaQuery} from '@vueuse/core';
const layout = ref('')
const isLargeScreen = useMediaQuery('(min-width: 1024px)');
const isMediumScreen = useMediaQuery('(min-width: 768px)');
watchEffect()
to track a change in either breakpoints. This is useful for a case where a user switches between desktop/tablet/mobile on the same browser window.watchEffect(() => {
updateLayout(isMediumScreen.value, isLargeScreen.value);
})
const updateLayout = (mediumScreen?: boolean, largeSreen?: boolean) => {
switch (true) {
case mediumScreen && !largeSreen:
layout.value = 'tablet'
break;
case largeSreen:
layout.value = 'desktop';
break;
default:
layout.value = 'mobile'
break;
}
}
NuxtLayout
<template>
<NuxtLayout :name="layout">
<NuxtPage />
</NuxtLayout>
</template>
After cloning/downloading the source files
npm - npm install
. Yarn - yarn install
npm- npm run dev -o
. Yarn - yarn dev -o
Navigate to http://localhost:3000/dashboard