For a specific URI, I am looking to display a different layout on the same route by using different components based on whether the user is on mobile or desktop. I want to avoid cluttering the PageCommon (layout component) with route path checks.
In the app, there is a main component responsible for the layout, featuring various router-views where different components are loaded for each page URI. This is a standard route setup.
{
path: '',
component: PageCommon,
children: [
{
path: '',
name: 'Home',
components: {
default: Home,
header: Header,
'main-menu': MainMenu,
'page-content': PageContent,
footer: Footer,
'content-footer': ContentFooter
}
},
Once a component is loaded, I cannot change the route components property. Therefore, I attempted to create a wrapper and dynamically pass the components.
{
path: 'my-view',
name: 'My_View',
component: () => import('@/components/MyView/ViewWrapper')
},
Within 'components/MyView/ViewWrapper':
<page-common v-if="isMobile">
<my-mobile-view is="default"></my-mobile-view>
<main-menu is="main-menu"></main-menu>
</page-common>
<page-common v-else>
<my-desktop-view is="default"></my-desktop-view>
<header is="header"></header>
<main-menu is="main-menu"></main-menu>
<footer is="footer"></footer>
</page-common>
</template>
Although I expected the components within the page-common block to be replaced with the appropriate ones, Vue simply loads the page-common component with empty router-views. Any suggestions on how to handle this?
I have already experimented with using the :is property to load different components, but I encounter difficulties in informing the parent to use a specific component for a particular page. Here is the code snippet for that:
<template>
<component :is="myView"></component>
</template>
<script>
import DesktopView from "@/components/MyView/DesktopView";
import MobileView from "@/components/MyView/MobileView";
export default {
name: 'MyView',
components: {
DesktopView,
MobileView,
},
data(){
return {
myView: null,
isMobile: this.detectMobile()
}
},
methods : {
getViewComponent() {
return this.isMobile ? 'mobile-view' : 'desktop-view';
}
},
created() {
this.myView = this.getViewComponent();
}
}
</script>
I could apply this approach to each of the PageCommon router views, creating a separate component for each to achieve the same functionality, but it does not seem like an optimal solution.