🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
>[success] # 路由嵌套 1. 嵌套路由当多个路由的组件都有相同的内容,可以将这些相同内容提取到**公共的组件当中** 2. 嵌套的时候在路由对象中增加`children`对象,负责嵌套路由创建的路由对象`children`属性实现,`childern`下路由需要被渲染的`<router-view> `是要写在起对应的上级视图组件中 * 路径为`/user/:id` 他是通过将`User` 组件渲染到外层的`<router-view> `,而嵌套组成后的路由`/user/:id/profile` 和` /user/:id/posts` 依次需要`User` 组件内的`<router-view> ` 来对应映射渲染组件`UserProfile` 和 `UserPosts` ![](https://img.kancloud.cn/d4/fe/d4fe8a394e4a2854909d93983aef3b92_816x276.png) ~~~ <div id="app"> <!--我渲染外层路由对应组件 User--> <router-view></router-view> </div> ~~~ ~~~ const User = { template: ` <div class="user"> <h2>User {{ $route.params.id }}</h2> <!--我渲染User 内部路由对应组件 --> <router-view></router-view> </div> `, } ~~~ ~~~js 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, }, ], }, ] ~~~ 3. 整渲染过程 **先加载外层组件 在加载内层组件(childern)** 当然路由过程也是如此**内外层合并后的整体作为路由地址**,说明一下以上面案例为例 访问地址`/user/:id` 他会渲染出来`User` 组件但不会渲染出`User `内部嵌套的`router-view` 组件 只有`/user/:id/profile` 路径能渲染出`User` 和内部嵌套的`profile` 4. 想让访问 `/user/:id/` 达到渲染出`User` 和内部嵌套的`profile`,可以提供一个空的嵌套路径 ~~~ const routes = [ { path: '/user/:id', component: User, children: [ // 当 /user/:id 匹配成功 // profile将被渲染到 User 的 <router-view> 内部 { path: '', component: profile}, // ...其他子路由 ], }, ] ~~~