Vue Router 是在 Vue.js 單頁應(yīng)用程序中創(chuàng)建路由的事實(shí)標(biāo)準(zhǔn)。但是,你是否知道,除了使用它將路由映射到頁面組件之外,還可以使用它來組合頁面布局?這是一個(gè)有趣的建議。讓我們看看如何實(shí)現(xiàn)。
該教程從基礎(chǔ)開始,介紹了Vue Router的概念,如何配置路由以及如何使用組合式API。它還介紹了如何在Vue Router中使用組合式API來創(chuàng)建布局。教程還包括如何使用路由鉤子函數(shù)和路由元信息來控制布局。
Vue Router 是在 Vue.js 單頁應(yīng)用程序中創(chuàng)建路由的事實(shí)標(biāo)準(zhǔn)。但是,你是否知道,除了使用它將路由映射到頁面組件之外,還可以使用它來組合頁面布局?這是一個(gè)有趣的建議。讓我們看看如何實(shí)現(xiàn)。
假設(shè)我們正在構(gòu)建一個(gè)博客,在該博客中,某些頁面可能在主要內(nèi)容的兩側(cè)都有側(cè)邊欄:

其他頁面只需要在內(nèi)容旁邊放置一個(gè)側(cè)邊欄,而且主內(nèi)容前后的位置可以變化。

而其他頁面則根本不需要側(cè)邊欄。

我們該如何完成這個(gè)任務(wù)?選項(xiàng)1是為側(cè)邊欄創(chuàng)建組件,并根據(jù)需要在每個(gè)頁面中包含它們。例如, AboutShow.vue 將獲得一個(gè)類似于以下內(nèi)容的路由記錄:
// router/index.js
{
path: '/about',
component: () => import('../pages/AboutShow.vue')
},
而相應(yīng)的頁面組件可能是這樣的:
// *AboutShow.vue
<template>
<div class="flex ...">
<SidebarOne />
<main>....</main>
<SidebarTwo />
</div>
</template>
<script setup>
import SidebarOne from "@/components/SidebarOne"
import SidebarTwo from "@/components/SidebarTwo"
</script>*
無論如何,關(guān)于頁面始終會(huì)與側(cè)邊欄相耦合。在大多數(shù)情況下,這可能并不是什么大問題。然而,讓我們考慮一種替代方法,即在路由器級別而不是頁面級別組成布局。
命名視圖
為了實(shí)現(xiàn)這一點(diǎn),我們將為路由記錄提供 components? (復(fù)數(shù))選項(xiàng),而不是 component (單數(shù))選項(xiàng):
{
path: '/about',
components: {
default: () => import('@/pages/AboutShow.vue'),
LeftSidebar: () => import('@/components/SidebarOne.vue'),
RightSidebar: () => import('@/components/SidebarTwo.vue'),
},
},
在這里,我們定義了關(guān)于路由應(yīng)該包括一個(gè)默認(rèn)組件,即關(guān)于頁面。這就是將顯示在RouterView?組件中。但是,它還應(yīng)該包括一個(gè) LeftSidebar? 組件,該組件映射到 SidebarOne? ,以及一個(gè) RightSidebar? 組件,該組件映射到 SidebarTwo 。
現(xiàn)在,為了讓 LeftSidebar? 和 RightSidebar? 組件知道在哪里顯示,我們必須使用額外的路由器視圖,稱為命名視圖,以及我們的默認(rèn)路由器視圖。我們還可以將路由器視圖包裝在帶有一些 Tailwind? 類的 div 中,以便美觀地布局。
<!-- App.vue -->
<template>
<!--...-->
<div class="sm:flex container p-5 mx-auto content justify-betweenflex-wrap">
<RouterView class="view main-content w-full order-2"></RouterView>
<RouterView name="LeftSidebar" class="view order-1 w-full"></RouterView>
<RouterView name="RightSidebar" class="view order-3 w-full"></RouterView>
</div>
<!--...-->
</template>
請注意,新的路由器視圖具有與我們提供給路由記錄的組件屬性的鍵相匹配的名稱屬性( LeftSidebar? 和 RightSidebar )
最后,這一次頁面本身可以完全排除側(cè)邊欄,結(jié)果是一樣的。
// *AboutShow.vue
<template>
<div>
<main>....</main>
</div>
</template>

這可能看起來有點(diǎn)繞,但現(xiàn)在很酷的是,有了這些額外的命名視圖,我們可以在任何新的路由記錄上靈活地添加一個(gè)或兩個(gè)側(cè)邊欄。
側(cè)邊欄

{
path: '/posts/:id',
components: {
default: () => import('@/pages/PostShow.vue'),
RightSidebar: () => import('@/components/SidebarTwo.vue'),
},
},
左側(cè)的側(cè)邊欄

//router/index.js
{
path: '/posts/:id',
components: {
default: () => import('@/pages/PostShow.vue'),
LeftSidebar: () => import('@/components/SidebarOne.vue'),
},
右側(cè)邊欄

//router/index.js
{
path: '/posts/',
components: {
default: () => import('@/pages/PostIndex.vue'),
RightSidebar: () => import('@/components/SidebarOne.vue'),
},
原文:https://vueschool.io/articles/vuejs-tutorials/composing-layouts-with-vue-router/