嵌套布局

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

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

示例

让我们将我们已经学到的所有概念结合起来构建一个完整的应用程序。

在这个示例中,我们有一个包含两个页面的站点:https://example.comhttps://example.com/about,我们希望为所有页面添加一个共同的页眉和页脚,页面之间唯一的区别是中间的内容。

┌───────────────────────────────────────────────────┐
│ Header                                            │
├─────────┬─────────────────────────────────────────┤
│ Menu    │ <ROUTE_SPECIFIC_CONTENT>                │
│ - home  │                                         │
│ - about │                                         │
│         │                                         │
├─────────┴─────────────────────────────────────────┤
│ Footer                                            │
└───────────────────────────────────────────────────┘

首先,我们创建三个组件:<Header><Footer><Menu>

开发人员可以手动将这些组件复制粘贴到每个页面组件中,但这样做重复且容易出错,相反,我们可以使用布局来自动重用公共部分

路由目录

src/
├── components/
   ├── header.tsx         # 页眉组件实现
   ├── footer.tsx         # 页脚组件实现
   └── menu.tsx           # 菜单组件实现
└── routes/
    ├── layout.tsx         # 使用 <Header>、<Footer> 和 <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$ } from '@builder.io/qwik';
 
export default component$(() => {
  return (
    <>
      <Header />
      <Menu />
      <Slot /> {/* <== 这是路由将被插入的地方 */}
      <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 <>主页</>;
});

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 <>关于</>;
});

当我们运行应用程序时,Qwik 将在 RootLayout 中渲染 About 组件

<RootLayout>
  <AboutPage />
</RootLayout>

Contributors

Thanks to all the contributors who have helped make this documentation better!

  • manucorporat
  • adamdbradley
  • Oyemade
  • mhevery
  • nnelgxorz
  • the-r3aper7