嵌套布局

布局为一组路由提供嵌套的 UI 和请求处理(中间件)

  • 共享请求处理:通过添加 onRequest 方法实现。
  • 共享 UI:通过 export default 一个 Qwik 组件实现。

示例

现在,将所有之前讨论的概念结合起来构建一个完整的应用程序。

在提议的示例中,您将注意到一个包含 2 个页面的网站:https://example.comhttps://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 目录下的所有路由。它将渲染 HeaderMenuFooter 组件,还会渲染 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 组件内渲染。即使没有引用 HeaderMenuFooter 组件,它仍然会与它们一起渲染。

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 组件内。即使没有引用 HeaderMenuFooter 组件,它仍然会与它们一起渲染。

src/routes/about/index.tsx
import { component$ } from '@builder.io/qwik';
 
export default component$(() => {
  return <>About</>;
});

当您运行应用程序时,Qwik 将渲染嵌套在 RootLayout 中的 About

<RootLayout>
  <AboutPage />
</RootLayout>

贡献者

感谢所有帮助改进本文档的贡献者!

  • manucorporat
  • adamdbradley
  • Oyemade
  • mhevery
  • nnelgxorz
  • the-r3aper7
  • mrhoodz
  • aendel
  • jemsco