当前位置:首页 > VUE

vue实现多级路由

2026-03-30 06:41:15VUE

实现多级路由的基本配置

在 Vue Router 中,多级路由通过嵌套的 children 属性实现。在路由配置文件中,为父路由添加 children 数组,定义子路由的路径和组件。

const routes = [
  {
    path: '/parent',
    component: ParentComponent,
    children: [
      {
        path: 'child',
        component: ChildComponent,
        children: [
          {
            path: 'grandchild',
            component: GrandChildComponent
          }
        ]
      }
    ]
  }
]

路由视图的嵌套

父组件中需使用 <router-view> 作为子路由的出口。多级嵌套时,每一层父组件都需要包含 <router-view> 标签。

<!-- ParentComponent.vue -->
<template>
  <div>
    <h1>Parent Component</h1>
    <router-view></router-view>
  </div>
</template>

动态路由匹配

多级路由支持动态路径参数,通过 : 标记动态字段。子路由可继承父路由的动态参数。

{
  path: '/user/:id',
  component: User,
  children: [
    {
      path: 'profile',
      component: UserProfile // 访问路径为 /user/123/profile
    }
  ]
}

路由重定向与别名

在嵌套路由中,可通过 redirect 实现默认子路由的自动跳转,或使用 alias 为路径设置别名。

{
  path: '/parent',
  redirect: '/parent/child', // 默认重定向到子路由
  children: [
    {
      path: 'child',
      alias: 'son', // 通过 /parent/son 也可访问
      component: ChildComponent
    }
  ]
}

路由守卫的应用

多级路由中,可通过 beforeEnter 或全局守卫实现权限控制。子路由会触发父路由的守卫。

{
  path: '/admin',
  component: Admin,
  beforeEnter: (to, from, next) => {
    // 父级路由守卫逻辑
  },
  children: [
    {
      path: 'dashboard',
      component: Dashboard,
      beforeEnter: (to, from, next) => {
        // 子路由专属守卫
      }
    }
  ]
}

代码分割与懒加载

结合动态导入实现路由组件的懒加载,优化多级路由的性能。使用 import() 语法分割代码块。

{
  path: '/lazy',
  component: () => import('./LazyParent.vue'),
  children: [
    {
      path: 'child',
      component: () => import('./LazyChild.vue')
    }
  ]
}

路径命名与编程式导航

为多级路由命名后,可通过 name 跳转。编程式导航支持传递多级路径参数。

vue实现多级路由

// 路由配置
{
  path: '/blog',
  name: 'blog',
  children: [
    {
      path: 'post/:id',
      name: 'blog.post'
    }
  ]
}

// 组件内跳转
this.$router.push({ name: 'blog.post', params: { id: 123 } })

注意事项

  • 子路由的 path 若以 / 开头会视为根路径,否则会相对父路径拼接
  • 嵌套过深时建议拆分路由模块,维护独立配置文件
  • 使用 router-link 时注意 to 属性的完整路径拼接
  • 可通过 v-if 结合路由元信息 (meta) 控制嵌套路由的显隐逻辑

标签: 路由vue
分享给朋友:

相关文章

vue 表格实现

vue 表格实现

Vue 表格实现方法 在 Vue 中实现表格功能可以通过多种方式完成,以下介绍几种常见的方法: 使用原生 HTML 表格 最简单的表格可以通过 Vue 模板中的原生 HTML 表格元素实现: &l…

vue实现适老化样式

vue实现适老化样式

Vue 实现适老化样式的关键方法 全局字体与字号调整 通过 CSS 变量或主题配置统一放大基础字号,建议正文不小于 18px,标题更大。在 App.vue 中设置全局样式: :root { --…

tabbar 实现 vue

tabbar 实现 vue

在 Vue 中实现 TabBar 功能可以通过多种方式完成,以下是几种常见的方法: 使用 Vue Router 结合自定义组件 创建一个自定义的 TabBar 组件,结合 Vue Router 实现…

vue实现selectable

vue实现selectable

Vue 实现可选择的 Select 组件 在 Vue 中实现一个可选择的 Select 组件,可以通过以下几种方式: 使用原生 HTML select 元素 <template> &…

vue 实现登录

vue 实现登录

Vue 实现登录功能 创建登录表单组件 在 Vue 项目中创建一个登录表单组件(如 Login.vue),包含用户名和密码输入框以及提交按钮。使用 v-model 实现双向数据绑定。 <tem…

vue 实现excel

vue 实现excel

Vue 实现 Excel 功能 前端导出 Excel 使用 xlsx 库可以轻松实现前端 Excel 导出功能。安装依赖: npm install xlsx 导出 Excel 示例代码: impo…