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

时间:2021-03-21 15:30:05

标签: vue.js vue-router

我正在尝试使用 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/> 组件

我哪里错了? 谢谢

1 个答案:

答案 0 :(得分:1)

您可能已经猜到了,<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 钩子中的两个子节点之一(可能基于某些逻辑)替换当前路由:

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

或者根据您希望导航历史的外观使用 $router.push()