路由参数
路由参数是URL的一部分,可以提取为参数在代码里使用。
想象一下,您有一个包含以下 URL 的页面,其中 [skuId] 可以是您数据库中数千种产品中的任何一种。
为每个产品创建一条路由是不切实际的。
因此,我们需要定义一个路由参数(URL 的一部分),其可用于提取[skuId]。
https://example.com/sku/[skuId]- 会匹配:
https://example.com/sku/1234 - 会匹配:
https://example.com/sku/xyz-567
- 会匹配:
https://example.com/sku/[skuId]/details- 会匹配:
https://example.com/sku/1234/details
- 会匹配:
src/
└── routes/
└── sku/
└── [skuId]/
├── index.tsx # https://example.com/sku/1234
└── details/
└── index.tsx # https://example.com/sku/1234/details
获取路由参数
使用useLocation() API获取路由参数。
import { useLocation } from '@builder.io/qwik-city';
export default component$(() => {
const location = useLocation();
return (
<div>
<h1>SKU</h1>
<p>Pathname: {location.pathname}</p>
<p>Sku Id: {location.params.skuId}</p>
</div>
);
});
捕获所有路由(Catch All Routes)
也可以通过添加像 [...slug] 这样的目录来创建一个catch-all routes。
这与上面描述的示例类似,但也会考虑 URI 的子段(即URL后面可以一直追加如/a/b/c/d,都能匹配到这条路由)。
它也可以应用于routes根目录级别。
src/
└── routes/
└── sku/
└── [...slug]/
└── index.tsx
上面目录结构会匹配:
https://example.com/sku/1234https://example.com/sku/1234/detailhttps://example.com/sku/1234/detail/edit- 等
可以通过子目录来限制catch-all routes,比如在[...slug]目录下创建end-of-route目录。
src/
└── routes/
└── sku/
└── [...slug]/
├── index.tsx
└── end-of-route/
└──index.tsx
上面目录结构会匹配:
https://example.com/sku/1234/5678/end-of-route