带有导航栏和侧边栏的 Vue 子路由

Vue subrouting with navbar and sidebar

我正在尝试使用 vue 设置路由系统。出于我的目的,我需要一个固定的顶部导航栏,它需要显示在每个页面上,还有一个侧边栏,我只想在设置页面上显示。按照 documentation 我尝试了:

const routes = [
  {
    path: '/settings',
    name: 'Settings',
    component: Settings,
    children: [
      {
        path: 'route1',
        name: 'Route1',
        component: Route1
      },
      {
        path: 'route2',
        name: 'Route2',
        component: Route2
      }
    ]
  }
]

然后在设置模板上:

<template>
  <div class="flex items-start">
    <div class="lg:w-3/12 w-12 sm:w-16 md:w-24 pb-10 lg:pr-8">
      <Sidebar />
    </div>
  </div>
  <div class="lg:w-9/12 w-full pt-10 pb-8 text-justify">
  // My subroute goes here  
  </div>
</template>

我觉得我错过了什么。首先,我不明白如何正确显示子路径。我尝试使用 <router-view /> 但它似乎指的是父导航。 其次,我不希望用户访问 /settings 路由,而只希望访问 /settings/route1settings/route2.

我可以通过简单地在每个设置路径中添加侧边栏来实现这一点,但这看起来很糟糕,因为它强制每次都安装 <Sidebar/> 组件

我哪里错了? 谢谢

您可能已经猜到,<router-view /> 元素进入您的 Settings 组件:

<template>
  <div class="flex items-start">
    <div class="lg:w-3/12 w-12 sm:w-16 md:w-24 pb-10 lg:pr-8">
      <Sidebar />
    </div>
  </div>
  <div class="lg:w-9/12 w-full pt-10 pb-8 text-justify">
    <router-view /> <!-- Here is your router view --> 
  </div>
</template>

然后正如评论中指出的那样,/settings 将始终是一条有效路线。 当客户端直接导航到 /settings 时,你可以做的是将当前路由替换为 mounted 钩子中的两个 children (可能基于某种逻辑)之一:

  mounted() {
    if(this.$router.currentRoute.path.endsWith('/settings')) {
      this.$router.replace('/settings/route1')
    }
  }

或者使用 $router.push(),而不是根据您希望导航历史记录的样子。