# 命名視圖
有時候想同時 (同級) 展示多個視圖,而不是嵌套展示,例如創建一個布局,有 `sidebar` (側導航) 和 `main` (主內容) 兩個視圖,這個時候命名視圖就派上用場了。你可以在界面中擁有多個單獨命名的視圖,而不是只有一個單獨的出口。如果 `router-view` 沒有設置名字,那么默認為 `default`。
~~~
<router-view class="view one"></router-view>
<router-view class="view two" name="a"></router-view>
<router-view class="view three" name="b"></router-view>
~~~
一個視圖使用一個組件渲染,因此對于同個路由,多個視圖就需要多個組件。確保正確使用 `components` 配置 (帶上 s):
~~~
const router = new VueRouter({
routes: [
{
path: '/',
components: {
default: Foo,
a: Bar,
b: Baz
}
}
]
})
~~~
以上案例相關的可運行代碼請[移步這里](https://jsfiddle.net/posva/6du90epg/)
[](https://jsfiddle.net/posva/6du90epg/)
。
## [#](https://router.vuejs.org/zh/guide/essentials/named-views.html#嵌套命名視圖) 嵌套命名視圖
我們也有可能使用命名視圖創建嵌套視圖的復雜布局。這時你也需要命名用到的嵌套 `router-view` 組件。我們以一個設置面板為例:
~~~
/settings/emails /settings/profile
+-----------------------------------+ +------------------------------+
| UserSettings | | UserSettings |
| +-----+-------------------------+ | | +-----+--------------------+ |
| | Nav | UserEmailsSubscriptions | | +------------> | | Nav | UserProfile | |
| | +-------------------------+ | | | +--------------------+ |
| | | | | | | | UserProfilePreview | |
| +-----+-------------------------+ | | +-----+--------------------+ |
+-----------------------------------+ +------------------------------+
~~~
* `Nav` 只是一個常規組件。
* `UserSettings` 是一個視圖組件。
* `UserEmailsSubscriptions`、`UserProfile`、`UserProfilePreview` 是嵌套的視圖組件。
**注意**:*我們先忘記 HTML/CSS 具體的布局的樣子,只專注在用到的組件上。*
`UserSettings` 組件的 `<template>` 部分應該是類似下面的這段代碼:
~~~
<!-- UserSettings.vue -->
<div>
<h1>User Settings</h1>
<NavBar/>
<router-view/>
<router-view name="helper"/>
</div>
~~~
*嵌套的視圖組件在此已經被忽略了,但是你可以在[這里](https://jsfiddle.net/posva/22wgksa3/)*
*找到完整的源代碼。*
然后你可以用這個路由配置完成該布局:
~~~
{
path: '/settings',
// 你也可以在頂級路由就配置命名視圖
component: UserSettings,
children: [{
path: 'emails',
component: UserEmailsSubscriptions
}, {
path: 'profile',
components: {
default: UserProfile,
helper: UserProfilePreview
}
}]
}
~~~
一個可以工作的示例的 demo 在[這里](https://jsfiddle.net/posva/22wgksa3/)
[](https://jsfiddle.net/posva/22wgksa3/)。