推荐答案
在 Vue Router 中,嵌套路由允许你在一个路由组件内部定义子路由。通过嵌套路由,你可以构建复杂的用户界面,其中不同的组件可以嵌套在父组件中,并且根据 URL 的变化动态加载这些子组件。
基本用法
- 定义嵌套路由:在路由配置中使用
children属性来定义嵌套路由。
// www.javascriptcn.com code example
const routes = [
{
path: '/parent',
component: ParentComponent,
children: [
{
path: 'child',
component: ChildComponent
}
]
}
]- 在父组件中使用
<router-view>:在父组件的模板中使用<router-view>来渲染子路由。
<!-- ParentComponent.vue -->
<template>
<div>
<h2>Parent Component</h2>
<router-view></router-view>
</div>
</template>- 访问嵌套路由:通过
/parent/child这样的 URL 访问嵌套路由。
动态嵌套路由
你也可以在嵌套路由中使用动态路径参数:
// www.javascriptcn.com code example
const routes = [
{
path: '/user/:id',
component: UserComponent,
children: [
{
path: 'profile',
component: UserProfileComponent
},
{
path: 'posts',
component: UserPostsComponent
}
]
}
]重定向和别名
你可以在嵌套路由中使用 redirect 和 alias:
// www.javascriptcn.com code example
const routes = [
{
path: '/parent',
component: ParentComponent,
children: [
{
path: '',
redirect: 'child'
},
{
path: 'child',
component: ChildComponent,
alias: 'kid'
}
]
}
]本题详细解读
嵌套路由的概念
嵌套路由是 Vue Router 提供的一种机制,允许你在一个路由组件内部定义子路由。这种机制非常适合构建复杂的用户界面,尤其是当你的应用有多个层级的路由时。
使用场景
- 多层级布局:例如,一个后台管理系统可能有多个层级的布局,每个层级对应不同的路由。
- 动态内容加载:根据 URL 的变化,动态加载不同的子组件。
- 模块化开发:将不同的功能模块拆分为子路由,便于维护和扩展。
注意事项
路径匹配:嵌套路由的路径是相对于父路由的路径。例如,如果父路由的路径是
/parent,那么子路由的路径child实际上匹配的是/parent/child。默认子路由:你可以通过
redirect属性来设置默认的子路由,当用户访问父路由时,自动重定向到某个子路由。路由守卫:嵌套路由同样支持路由守卫(如
beforeEnter、beforeRouteEnter等),你可以在父路由或子路由中定义守卫来控制导航。命名视图:如果你有多个
<router-view>,可以使用命名视图来指定不同的子路由渲染到不同的视图。
示例代码
// www.javascriptcn.com code example
const routes = [
{
path: '/dashboard',
component: DashboardLayout,
children: [
{
path: '',
component: DashboardHome
},
{
path: 'settings',
component: DashboardSettings
},
{
path: 'profile',
component: DashboardProfile
}
]
}
]在这个例子中,/dashboard 是父路由,/dashboard/settings 和 /dashboard/profile 是子路由。当用户访问 /dashboard 时,默认会渲染 DashboardHome 组件。