菜单

菜单允许您以简单的声明方式描述网站导航结构。菜单分为两个步骤:

  1. 定义一个包含所在目录菜单结构的 menu.md 文件。
  2. 使用 useContent() 函数在模板中检索菜单结构以进行渲染。在此处阅读更多

文件结构

首先按照以下方式布局文件:

src/
└── routes/
    └── some/
        ├── menu.md
        ├── layout.tsx
        └── path/
            └── index.tsx  # https://example.com/some/path

访问 https://example.com/some/path 会激活:

  • src/routes/some/path/index.tsx:此组件将用于渲染页面内容。
  • src/routes/some/layout.tsx:此布局将用于为 src/routes/some/path/index.tsx 提供内容。在内部,布局可以使用 src/routes/some/menu.md 来渲染菜单。
  • src/routes/some/menu.md:此文件将用于声明菜单结构,该结构将由 src/routes/some/layout.tsx 渲染。

声明菜单结构

使用 menu.md 来声明菜单结构。

  • 使用标题 (#, ## 等) 来定义菜单深度。
  • 使用项目符号 (-) 来定义菜单项。
src/route/some/menu.md
# 文档
 
## 开始入门
 
- [介绍](introduction/index.md)
 
## 组件
 
- [基础](/docs/(qwik)/components/basics/index.mdx)

检索菜单结构

在运行时,任何组件都可以使用 useContent() 钩子函数检索菜单。返回的类型是 ContentMenu

上面的示例将返回:

{
  text: "文档",
  items: [
    {
      text: "开始入门",
      items: [
        {
          text: "介绍",
          href: "/docs/introduction"
        }
      ],
    },
    {
      text: "组件",
      items: [
        {
          text: "基础",
          href: "/docs/(qwik)/components/basics"
        }
      ],
    },
  ],
}

在布局中使用 ContentMenu

虽然 useContent() 可以从当前路由的任何组件中调用,但通常在布局组件(或布局使用的组件)中使用它来渲染菜单。以下是一个示例用法:

import { component$ } from '@builder.io/qwik';
import { useLocation, useContent } from '@builder.io/qwik-city';
export default component$(() => {
  const { menu } = useContent();
  const { url } = useLocation();
 
  return (
    <nav class="menu">
      {menu
        ? menu.items?.map((item) => (
            <>
              <h5>{item.text}</h5>
              <ul>
                {item.items?.map((item) => (
                  <li>
                    <a
                      href={item.href}
                      class={{
                        'is-active': url.pathname === item.href,
                      }}
                    >
                      {item.text}
                    </a>
                  </li>
                ))}
              </ul>
            </>
          ))
        : null}
    </nav>
  );
});

Contributors

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

  • manucorporat
  • adamdbradley
  • the-r3aper7
  • Oyemade
  • mhevery
  • nnelgxorz
  • jakovljevic-mladen
  • cunzaizhuyi
  • AnthonyPAlicea
  • hamatoyogi