VueRouter 基础教程系列 🎉
嵌套路由的 URL 路径片段往往对应着嵌套的组件结构。
实现嵌套路由的两个必要要素:
- 要嵌套的组件必须要包含一个
<router-view>组件,作为被嵌套组件的渲染出口。 - 路由配置中要通过
children来为父级路由定义子级的路由。
具体示例:
const User = {
template: `
<div class="user">
<h2>User {{ $route.params.id }}</h2>
<router-view></router-view>
</div>
`
}
const routes = [
{
path: '/user/:id',
component: User,
children: [
{
// 当 /user/:id/profile 匹配成功
// UserProfile 将被渲染到 User 的 <router-view> 内部
path: 'profile',
component: UserProfile,
},
{
// 当 /user/:id/posts 匹配成功
// UserPosts 将被渲染到 User 的 <router-view> 内部
path: 'posts',
component: UserPosts,
},
],
},
]
注意,以
/开头的嵌套路径将被视为根路径。这允许你利用组件嵌套,但不必使用嵌套的 URL。
{
path:'/router',
children:[
{
path:'/view' //无法通过 /router/view 访问。但可以通过 `/view` 访问。
},
{
path:'route' //可以通过 /router/route 访问
}
]
}
下面来看下嵌套路由的命中情况。
/router/router success ✔️
/router/view failed ❌
/view success ✔️