Skip to main content
基本 Svelte
介绍
反应性
属性
逻辑
事件
绑定
类和样式
动作
转换
高级 Svelte
高级反应性
重用内容
运动
高级绑定
高级转换
上下文 API
特殊元素
<script module>
后续步骤
基本 SvelteKit
介绍
路由
加载数据
标题和 cookie
共享模块
表单
API 路由
$app/state
错误和重定向
高级 SvelteKit
钩子
页面选项
链接选项
高级路由
高级加载
环境变量
结论

要匹配未知数量的路径段,请使用 [...rest] 参数,该参数因与 JavaScript 中的 rest 参数 相似而得名。

¥To match an unknown number of path segments, use a [...rest] parameter, so named for its resemblance to rest parameters in JavaScript.

src/routes/[path] 重命名为 src/routes/[...path]。路由现在匹配任何路径。

¥Rename src/routes/[path] to src/routes/[...path]. The route now matches any path.

将首先测试其他更具体的路由,使其余参数可用作 ‘catch-all’ 路由。例如,如果你需要为 /categories/... 内的页面自定义 404 页面,你可以添加以下文件:

¥[!NOTE] Other, more specific routes will be tested first, making rest parameters useful as ‘catch-all’ routes. For example, if you needed a custom 404 page for pages inside /categories/..., you could add these files:

src/routes/
├ categories/
│ ├ animal/
│ ├ mineral/
│ ├ vegetable/
│ ├ [...catchall]/
│ │ ├ +error.svelte
│ │ └ +page.server.js

+page.server.js 文件中,error(404)load 中。

¥Inside the +page.server.js file, error(404) inside load.

剩余参数不需要放在最后 — 像 /items/[...path]/edit/items/[...path].json 这样的路由完全有效。

¥Rest parameters do not need to go at the end — a route like /items/[...path]/edit or /items/[...path].json is totally valid.

上一页 下一页
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
<script>
	import { page } from '$app/state';
 
	let words = ['how', 'deep', 'does', 'the', 'rabbit', 'hole', 'go'];
 
	let depth = $derived(page.params.path.split('/').filter(Boolean).length);
	let next = $derived(depth === words.length ? '/' : `/${words.slice(0, depth + 1).join('/')}`);
</script>
 
<div class="flex">
	{#each words.slice(0, depth) as word}
		<p>{word}</p>
	{/each}
 
	<p><a href={next}>{words[depth] ?? '?'}</a></p>
</div>
 
<style>
	.flex {
		display: flex;
		height: 100%;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}
 
	p {
		margin: 0.5rem 0;
		line-height: 1;
	}
 
	a {
		display: flex;
		width: 100%;
		height: 100%;
		align-items: center;
		justify-content: center;
		font-size: 4rem;
	}
</style>