当前位置:首页 > VUE

vue实现多级路由

2026-03-09 18:57:53VUE

Vue 多级路由实现方法

Vue Router 支持嵌套路由(多级路由),通过 children 配置实现层级关系。以下是具体实现方式:

路由配置

router/index.js 中定义嵌套路由结构:

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

路由视图渲染

父级组件需要包含 <router-view> 用于渲染子路由:

<!-- ParentComponent.vue -->
<template>
  <div>
    <h2>父级组件</h2>
    <router-view></router-view>
  </div>
</template>

动态路由匹配

可通过冒号 : 实现动态路径参数:

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

命名路由

为路由设置 name 属性便于跳转:

{
  path: '/settings',
  name: 'settings',
  component: Settings,
  children: [
    {
      path: 'account',
      name: 'settings.account',
      component: AccountSettings
    }
  ]
}

编程式导航

在组件中使用 $router 进行跳转:

this.$router.push('/parent/child/grandchild')
// 或使用命名路由
this.$router.push({ name: 'settings.account' })

路由守卫

可为嵌套路由设置导航守卫:

router.beforeEach((to, from, next) => {
  if (to.matched.some(record => record.meta.requiresAuth)) {
    // 验证逻辑
  }
  next()
})

默认子路由

设置空路径作为默认渲染的子路由:

{
  path: '/dashboard',
  component: Dashboard,
  children: [
    {
      path: '',
      component: DashboardDefault
    },
    {
      path: 'analytics',
      component: DashboardAnalytics
    }
  ]
}

实现多级路由时需注意:

vue实现多级路由

  • 路径拼接规则:子路由 path 会基于父路由 path 自动拼接
  • 组件结构:每级路由对应的组件都需要包含 <router-view> 容器
  • 路由激活状态:可使用 router-link-exact-active 类名设置样式

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

相关文章

vue实现hover

vue实现hover

Vue 实现 hover 效果的方法 在 Vue 中实现 hover 效果可以通过多种方式实现,包括使用 CSS、Vue 指令或事件监听。以下是几种常见的方法: 使用 CSS :hover 伪类 通…

vue实现录像

vue实现录像

Vue 实现录像功能 在 Vue 中实现录像功能通常需要借助浏览器的 MediaDevices API 和 MediaRecorder API。以下是实现步骤: 获取用户摄像头和麦克风权限 使用 n…

vue实现增删

vue实现增删

Vue 实现增删功能 在 Vue 中实现增删功能通常涉及数据绑定、事件处理和列表渲染。以下是基于 Vue 2 或 Vue 3 的实现方法: 数据定义 初始化一个数组用于存储列表数据,并在 Vue 实…

vue 实现 confirm

vue 实现 confirm

实现确认对话框的方法 在Vue中实现确认对话框可以通过多种方式完成,包括使用内置组件、第三方库或自定义组件。 使用浏览器原生confirm 最简单的实现方式是直接调用浏览器原生的confirm方法。…

vue实现框选

vue实现框选

Vue 实现框选功能 在 Vue 中实现框选功能通常需要监听鼠标事件,计算选区范围,并根据选区范围高亮或选中元素。以下是实现框选功能的关键步骤。 监听鼠标事件 在 Vue 模板中,为容器元素绑定鼠标…

vue实现双击

vue实现双击

Vue 实现双击事件的方法 在Vue中实现双击事件可以通过以下几种方式完成,具体选择取决于项目需求和开发习惯。 使用 @dblclick 指令 Vue提供了内置的@dblclick指令,可以直接在模…