選單

選單允許您以簡單的宣告方式描述網站導航結構。選單分為兩個步驟

  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
# Docs
 
## Getting Started
 
- [Introduction](introduction/index.md)
 
## Components
 
- [Basics](/docs/(qwik)/components/basics/index.mdx)

取得選單結構

在執行時,任何元件都可以使用 useContent() 鉤子取得選單。返回的類型為 ContentMenu

上面的示例將返回

{
  text: "Docs",
  items: [
    {
      text: "Getting Started",
      items: [
        {
          text: "Introduction",
          href: "/docs/introduction"
        }
      ],
    },
    {
      text: "Components",
      items: [
        {
          text: "Basics",
          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, index) => (
            <div key={index}>
              <h5>{item.text}</h5>
              <ul>
                {item.items?.map((item, subIndex) => (
                  <li key={`item-${index}-${subIndex}`}>
                    <a
                      href={item.href}
                      class={{
                        'is-active': url.pathname === item.href,
                      }}
                    >
                      {item.text}
                    </a>
                  </li>
                ))}
              </ul>
            </div>
          ))
        : null}
    </nav>
  );
});

貢獻者

感謝所有幫助改進此文件的貢獻者!

  • manucorporat
  • adamdbradley
  • the-r3aper7
  • Oyemade
  • mhevery
  • nnelgxorz
  • jakovljevic-mladen
  • cunzaizhuyi
  • AnthonyPAlicea
  • mrhoodz
  • hamatoyogi
  • dejurin
  • gioboa
  • jemsco