要匹配未知数量的路径段,请使用 [...rest] 参数,之所以这样命名是因为它类似于 JavaScript 中的剩余参数。
将 src/routes/[path] 重命名为 src/routes/[...path]。现在这个路由可以匹配任意路径。
其他更具体的路由会首先被测试,这使得剩余参数在作为 “catch-all” 路由时很有用。例如,如果你需要为
/categories/...内的页面创建自定义 404 页面,你可以添加这些文件:src/routes/ ├ categories/ │ ├ animal/ │ ├ mineral/ │ ├ vegetable/ │ ├ [...catchall]/ │ │ ├ +error.svelte │ │ └ +page.server.js在
+page.server.js文件中,error(404)位于load内。
剩余参数不一定要放在末尾 — 像 /items/[...path]/edit 或 /items/[...path].json 这样的路由也是完全有效的。
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>