首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用导航栏和侧边栏的Vue子路由

使用导航栏和侧边栏的Vue子路由
EN

Stack Overflow用户
提问于 2021-03-21 23:30:05
回答 1查看 133关注 0票数 0

我正在试着用vue建立一个路由系统。对于我的目的,我需要在顶部的固定导航栏,需要显示在每个页面和侧栏,我想只显示在设置页面上。遵循我尝试过的documentation

代码语言:javascript
复制
const routes = [
  {
    path: '/settings',
    name: 'Settings',
    component: Settings,
    children: [
      {
        path: 'route1',
        name: 'Route1',
        component: Route1
      },
      {
        path: 'route2',
        name: 'Route2',
        component: Route2
      }
    ]
  }
]

然后在设置模板上:

代码语言:javascript
复制
<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/>组件

我哪里错了?谢谢

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-03-22 05:37:30

正如您可能已经猜到的,<router-view />元素位于您的Settings组件中:

代码语言:javascript
复制
<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钩子中的两个子路径中的一个(可能基于某些逻辑):

代码语言:javascript
复制
  mounted() {
    if(this.$router.currentRoute.path.endsWith('/settings')) {
      this.$router.replace('/settings/route1')
    }
  }

或者根据您想要的导航历史记录的外观使用$router.push()

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66734194

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档