当前位置:首页 > VUE

如何实现vue路由嵌套

2026-02-24 22:28:02VUE

实现 Vue 路由嵌套

在 Vue Router 中,路由嵌套是通过 children 配置项实现的。嵌套路由允许在父路由组件中渲染子路由组件,适用于多层级页面结构。

基本配置方法

  1. 定义路由配置 在路由配置文件中,通过 children 属性定义嵌套路由。父路由需设置 component,子路由路径可以是相对路径或绝对路径。
const routes = [
  {
    path: '/parent',
    component: ParentComponent,
    children: [
      {
        path: 'child', // 相对路径,实际路径为 /parent/child
        component: ChildComponent
      },
      {
        path: '/parent/another-child', // 绝对路径
        component: AnotherChildComponent
      }
    ]
  }
]
  1. 父组件中放置 <router-view> 父路由组件模板中需预留 <router-view> 作为子路由的出口。
<!-- ParentComponent.vue -->
<template>
  <div>
    <h2>父组件</h2>
    <router-view></router-view>
  </div>
</template>

动态路由嵌套

嵌套路由支持动态路径参数,参数会传递给子组件。

如何实现vue路由嵌套

const routes = [
  {
    path: '/user/:id',
    component: User,
    children: [
      {
        path: 'profile',
        component: UserProfile
      }
    ]
  }
]

默认子路由

通过空路径设置默认子路由,当访问父路由时自动渲染该子路由。

如何实现vue路由嵌套

const routes = [
  {
    path: '/dashboard',
    component: Dashboard,
    children: [
      {
        path: '', // 默认子路由
        component: DashboardDefault
      },
      {
        path: 'stats',
        component: DashboardStats
      }
    ]
  }
]

命名视图嵌套

对于命名视图,需在子路由中同样指定 components 选项。

const routes = [
  {
    path: '/layout',
    components: {
      default: Layout,
      sidebar: Sidebar
    },
    children: [
      {
        path: 'content',
        components: {
          default: Content,
          sidebar: ContentSidebar
        }
      }
    ]
  }
]

路由跳转

在模板或代码中导航到嵌套路由时,路径需包含完整层级。

<router-link to="/parent/child">跳转子路由</router-link>
router.push('/parent/child')

注意事项

  • 嵌套路由的路径匹配是累积的,父路由路径会作为前缀
  • 子路由组件会继承父路由的 $route 对象
  • 确保每个嵌套层级都有对应的 <router-view> 出口
  • 对于复杂嵌套,考虑使用路由模块化拆分配置

标签: 嵌套路由
分享给朋友:

相关文章

vue实现路由跳转

vue实现路由跳转

Vue 路由跳转的实现方式 在 Vue 中,路由跳转可以通过 vue-router 实现,以下是几种常见的方法: 声明式导航(模板中使用 <router-link>) 通过 <ro…

vue路由跳转实现

vue路由跳转实现

Vue 路由跳转实现方法 在 Vue 中,路由跳转可以通过多种方式实现,以下是常见的几种方法: 声明式导航(模板中使用 <router-link>) 通过 <router-link…

vue实现路由后退

vue实现路由后退

路由后退的实现方法 在Vue中实现路由后退功能,可以通过Vue Router提供的方法来完成。以下是几种常见的实现方式: 使用router.go()方法 // 在组件中调用 this.$route…

动态路由vue实现

动态路由vue实现

动态路由的实现方式 在Vue中实现动态路由通常有两种主要方式:基于用户权限的动态路由和基于参数变化的动态路由。这两种方式都能有效提升应用灵活性。 基于用户权限的动态路由 通过用户角色或权限动态生成可…

vue实现路由弹窗

vue实现路由弹窗

vue实现路由弹窗的方法 在Vue中实现路由弹窗可以通过多种方式完成,以下是几种常见的实现方法: 使用动态路由和组件 在路由配置中定义一个动态路由,用于渲染弹窗组件。这种方法适用于需要根据路由参数动…

不用vue实现切换路由

不用vue实现切换路由

使用原生 JavaScript 实现路由切换 通过监听 URL 变化并动态加载内容,可以实现简单的路由切换功能。以下是一个基于 history.pushState 和 popstate 事件的实现方式…