user1833620
user1833620

Reputation: 781

Hide sidebar component some page in VUE.js

I am working with Vue.js and I have a question.

Is there a way to hide sidebar component only some page ? This is my code below.

router.js

  const routes = [
  {
    path: '/',
    redirect: '/home',
    component: () => import('@/layout/MainLayout'),
    children: [
      {
        path: 'home',
        name: 'Home',
        component: () => import('Views/Home.vue'),
      }, 
    ],
  },
  {
    path: '/subpage',
    redirect: '/subpage/subpage',
    component: () => import('@/layout/MainLayout'),
    children: [ 
      {
        path: 'subpage',
        name: 'Subpage',
        component: () => import('Views/Subpage/Subpage.vue'),
      }, 
    ],
  }, 
];

MainLayout.vue

<template>
  <div id="content" class="content"> 
    <router-view></router-view> 
    <Sidebar></Sidebar> 
  </div>
</template>

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

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

Do I need to make another layout? like MainLayout2.vue

Please help.

Upvotes: 4

Views: 1916

Answers (1)

Faran Ali
Faran Ali

Reputation: 482

You can add meta information to vue routes. Add the sidebar key to the routes you want to hide

{
path: '/subpage',
redirect: '/subpage/subpage',
component: () => import('@/layout/MainLayout'),
children: [ 
  {
    path: 'subpage',
    name: 'Subpage',
    meta:{sidebar:false}
    component: () => import('Views/Subpage/Subpage.vue'),
  }, 
],
}, 

Then in your layout component, make a computed property to check if the current route needs to hide the sidebar

computed:{
    shouldShowSidebar(){
        return this.$route.meta.sidebar!==false;
    }
}

Then use this computed property to conditionally hide the sidebar on specific routes

<Sidebar v-if="shouldShowSidebar"></Sidebar> 

You can add meta:{sidebar:false} to any route you want the sidebar to be hidden on

Upvotes: 6

Related Questions