歡迎觀看《Vue Router 實戰(第4版)》視頻課程
一些應用程序的 UI 由多層嵌套的組件組成。在這種情況下,URL 的片段通常對應于特定的嵌套組件結構,例如:
通過 Vue Router,你可以使用嵌套路由配置來表達這種關系。
接著上節創建的 app :
<!-- App.vue -->
<template>
??<router-view />
</template>
<!-- User.vue -->
<template>
??<div>
????User {{ $route.params.id }}
??</div>
</template>
import User from './User.vue'
// 這些都會傳遞給 `createRouter`
const routes = [{ path: '/user/:id', component: User }]
這里的 <router-view> 是一個頂層的 router-view。它渲染頂層路由匹配的組件。同樣地,一個被渲染的組件也可以包含自己嵌套的 <router-view>。例如,如果我們在 User 組件的模板內添加一個 <router-view>:
<!-- User.vue -->
<template>
??<div class="user">
????<h2>User {{ $route.params.id }}</h2>
????<router-view />
??</div>
</template>
要將組件渲染到這個嵌套的 router-view 中,我們需要在路由中配置 children:
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。
如你所見,children 配置只是另一個路由數組,就像 routes 本身一樣。因此,你可以根據自己的需要,不斷地嵌套視圖。
此時,按照上面的配置,當你訪問 /user/eduardo 時,在 User 的 router-view 里面什么都不會呈現,因為沒有匹配到嵌套路由。也許你確實想在那里渲染一些東西。在這種情況下,你可以提供一個空的嵌套路徑:
const routes = [
??{
????path: '/user/:id',
????component: User,
????children: [
??????// 當 /user/:id 匹配成功
??????// UserHome 將被渲染到 User 的 <router-view> 內部
??????{ path: '', component: UserHome },
??????// ...其他子路由
????],
??},
]
這個例子的 demo 可以在這里找到。
在處理命名路由時,你通常會給子路由命名:
const routes = [
??{
????path: '/user/:id',
????component: User,
????// 請注意,只有子路由具有名稱
????children: [{ path: '', name: 'user', component: UserHome }],
??},
]
這將確保導航到 /user/:id 時始終顯示嵌套路由。
在一些場景中,你可能希望導航到命名路由而不導航到嵌套路由。例如,你想導航 /user/:id 而不顯示嵌套路由。那樣的話,你還可以命名父路由,但請注意重新加載頁面將始終顯示嵌套的子路由,因為它被視為指向路徑/users/:id 的導航,而不是命名路由:
const routes = [
??{
????path: '/user/:id',
????name: 'user-parent',
????component: User,
????children: [{ path: '', name: 'user', component: UserHome }],
??},
]
我們還可以僅利用路由的父子關系,但不嵌套路由組件。這對于將具有公共路徑前綴的路由分組在一起或使用更高級的功能時很有用,例如:路由獨享的守衛或路由元信息。
為了實現這一點, 我們在父路由中省略了 component 和 components 選項
const routes = [
??{
????path: '/admin',
????children: [
??????{ path: '', component: AdminOverview },
??????{ path: 'users', component: AdminUserList },
??????{ path: 'users/:id', component: AdminUserDetails },
????],
??},
]
由于父級沒有指定路由組件,頂級 <router-view> 將跳過父級并僅使用子路由組件。