【问题标题】:Vue subrouting with navbar and sidebar带有导航栏和侧边栏的 Vue 子路由
【发布时间】:2021-03-21 15:30:05
【问题描述】:

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

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

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

我哪里错了? 谢谢

【问题讨论】:

  • 您好,由于您使用的是嵌套路由,那么它总是会引用父导航,并且要显示您需要使用&lt;router-view&gt;&lt;/router-view&gt;的嵌套路由。

标签: vue.js vue-router


【解决方案1】:

您可能已经猜到了,&lt;router-view /&gt; 元素位于您的 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>

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

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

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

【讨论】:

    猜你喜欢
    • 2019-11-25
    • 2014-07-03
    • 1970-01-01
    • 2021-03-14
    • 2020-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-22
    相关资源
    最近更新 更多