首页 > 解决方案 > 在 VUE.js 中隐藏某些页面的侧边栏组件

问题描述

我正在使用 Vue.js,我有一个问题。

有没有办法sidebar只隐藏某个页面的组件?这是我下面的代码。

路由器.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'),
      }, 
    ],
  }, 
];

主布局.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>

我需要制作另一个布局吗?喜欢MainLayout2.vue

请帮忙。

标签: vue.js

解决方案


您可以将元信息添加到 vue 路由。将侧边栏键添加到要隐藏的路线

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

然后在你的布局组件中,创建一个计算属性来检查当前路由是否需要隐藏侧边栏

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

然后使用此计算属性有条件地隐藏特定路线上的侧边栏

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

您可以添加meta:{sidebar:false}到任何希望隐藏侧边栏的路线


推荐阅读