巢狀佈局
佈局為一組路由提供巢狀 UI 和請求處理(中介軟體)
- 共用請求處理:透過新增
onRequest
方法完成。 - 共用 UI:透過
export default
Qwik 元件完成。
範例
現在,結合之前討論的所有概念來建置一個完整的應用程式。
在這個範例中,您會看到一個包含 2 個頁面的網站:https://example.com
和 https://example.com/about
。目標是為所有頁面添加一個通用的頁首和頁尾,頁面之間的唯一區別是中間的內容。
┌───────────────────────────────────────────────────┐
│ Header │
├─────────┬─────────────────────────────────────────┤
│ Menu │ <ROUTE_SPECIFIC_CONTENT> │
│ - home │ │
│ - about │ │
│ │ │
├─────────┴─────────────────────────────────────────┤
│ Footer │
└───────────────────────────────────────────────────┘
首先,建立三個元件:<Header>
、<Footer>
和 <Menu>
。
開發人員可以手動將這些元件複製並貼上到每個頁面元件中,但這樣做重複且容易出錯。應該使用佈局來自動重複使用通用部分。
路由目錄
src/
├── components/
│ ├── header.tsx # Header component implementation
│ ├── footer.tsx # Footer component implementation
│ └── menu.tsx # Menu component implementation
└── routes/
├── layout.tsx # Layout implementation using: <Header>, <Footer>, and <Menu>
├── about/
│ └── index.tsx # https://example.com/about
└── index.tsx # https://example.com
src/routes/layout.tsx
它將用於 src/routes
目錄下的所有路由。它將渲染 Header
、Menu
和 Footer
元件,並在 Slot
元件下渲染嵌套路由。
src/routes/layout.tsx
import { component$, Slot } from '@builder.io/qwik';
export default component$(() => {
return (
<>
<Header />
<Menu />
<Slot /> {/* <== This is where the route will be inserted */}
<Footer />
</>
);
});
src/routes/index.tsx
這是網站的主路由。它將在 src/routes/layout.tsx
檔案的 Slot
元件中渲染。即使沒有引用 Header
、Menu
或 Footer
元件,它仍然會與它們一起渲染。
src/routes/index.tsx
import { component$ } from '@builder.io/qwik';
export default component$(() => {
return <>Home</>;
});
src/routes/about/index.tsx
與 src/routes/index.tsx
檔案類似,about
路由也將在 src/routes/layout.tsx
檔案的 Slot
元件中渲染。即使沒有引用 Header
、Menu
或 Footer
元件,它仍然會與它們一起渲染。
src/routes/about/index.tsx
import { component$ } from '@builder.io/qwik';
export default component$(() => {
return <>About</>;
});
當您運行應用程式時,Qwik 將會渲染嵌套在 RootLayout
內的 About
<RootLayout>
<AboutPage />
</RootLayout>