因為我們使用 <form>
,即使使用者沒有 JavaScript,我們的應用程式也能正常運作(這種情況發生的頻率比您想像的要高)。這很好,因為這意味著我們的應用程式具有彈性。
大多數情況下,使用者確實有 JavaScript。在這些情況下,我們可以漸進式增強體驗,就像 SvelteKit 使用客戶端路由漸進式增強 <a>
元素一樣。
從 $app/forms
導入 enhance
函式...
src/routes/+page
<script>
import { enhance } from '$app/forms';
let { data, form } = $props();
</script>
...並將 use:enhance
指令新增至 <form>
元素
src/routes/+page
<form method="POST" action="?/create" use:enhance>
src/routes/+page
<form method="POST" action="?/delete" use:enhance>
就是這樣!現在,當 JavaScript 啟用時,use:enhance
將模擬瀏覽器原生的行為,除了完整頁面重新載入之外。它將
- 更新
form
屬性 - 在成功回應時使所有資料失效,導致
load
函式重新執行 - 在重新導向回應時導覽至新頁面
- 如果發生錯誤,則渲染最近的錯誤頁面
既然我們正在更新頁面而不是重新載入它,我們可以使用轉場效果等花俏的東西
src/routes/+page
<script>
import { fly, slide } from 'svelte/transition';
import { enhance } from '$app/forms';
let { data, form } = $props();
</script>
src/routes/+page
<li in:fly={{ y: 20 }} out:slide>...</li>
上一個 下一個
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
<script>
let { data, form } = $props();
</script>
<div class="centered">
<h1>todos</h1>
{#if form?.error}
<p class="error">{form.error}</p>
{/if}
<form method="POST" action="?/create">
<label>
add a todo:
<input
name="description"
value={form?.description ?? ''}
autocomplete="off"
required
/>
</label>
</form>
<ul class="todos">
{#each data.todos as todo (todo.id)}
<li>
<form method="POST" action="?/delete">
<input type="hidden" name="id" value={todo.id} />
<span>{todo.description}</span>
<button aria-label="Mark as complete"></button>
</form>
</li>
{/each}
</ul>
</div>
<style>
.centered {
max-width: 20em;
margin: 0 auto;
}
label {
width: 100%;
}
input {
flex: 1;
}
span {
flex: 1;
}
button {
border: none;
background: url(./remove.svg) no-repeat 50% 50%;
background-size: 1rem 1rem;
cursor: pointer;
height: 100%;
aspect-ratio: 1;
opacity: 0.5;
transition: opacity 0.2s;
}
button:hover {
opacity: 1;
}
.saving {
opacity: 0.5;
}
</style>