Nếu không định trước số lượng phân đoạn đường dẫn, bạn có thể sử dụng tham số [...rest], được đặt tên như vậy vì nó giống với rest parameters trong JavaScript.
Đổi tên src/routes/[path] thành src/routes/[...path]. Bây giờ, route này sẽ phù hợp với bất kỳ đường dẫn nào.
Các route cụ thể hơn sẽ được kiểm tra trước, khiến rest parameters trở nên hữu ích như một route 'catch all'. Ví dụ, nếu bạn cần tùy chỉnh trang 404 cho các trang
/categories/..., bạn có thể thêm các tệp sau:src/routes/ ├ categories/ │ ├ animal/ │ ├ mineral/ │ ├ vegetable/ │ ├ [...catchall]/ │ │ ├ +error.svelte │ │ └ +page.server.jsTrong tệp
+page.server.js,throw error(404)trong hàmload.
Rest parameters không cần phải ở cuối cùng - một route như /items/[...path]/edit hoặc /items/[...path].json là hoàn toàn hợp lệ.
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/stores';let words = ['how', 'deep', 'does', 'the', 'rabbit', 'hole', 'go'];
$: depth = $page.params.path.split('/').filter(Boolean).length; $: next = 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>