因为我们使用的是 <form>
,我们的应用可以在用户没有 JavaScript 的时候依然有效,这种情况可能比想象中要更常见。这挺好,因为这代表我们的应用是有弹性的。
但大部分时候,用户还是 有 JavaScript 的。在这种情况下,我们可以 逐步增强 用户体验,就像 SvelteKit 使用客户端路由增强 <a>
元素一样。
从 $app/forms
导入 enhance
函数……
src/routes/+page.svelte
<script>
import { enhance } from '$app/forms';
export let data;
export let form;
</script>
……然后给 <form>
元素添加 use:enhance
标志:
src/routes/+page.svelte
<form method="POST" action="?/create" use:enhance>
src/routes/+page.svelte
<form method="POST" action="?/delete" use:enhance>
然后就完事了!现在,当 JavaScript 可用时,use:enhance
会模仿浏览器原生的行为,而不是把整个页面重载,包括如下几件事:
- 更新
form
属性(prop) - 成功响应后无效化所有数据,触发
load
函数重载(re-run) - 通过重定向响应导航到新页面
- 如果发生错误则渲染最近的错误页面
既然我们现在是更新页面而非重载页面,我们可以使用比如过渡添加一些有意思的效果了:
src/routes/+page.svelte
<script>
import { fly, slide } from 'svelte/transition';
import { enhance } from '$app/forms';
export let data;
export let form;
</script>
src/routes/+page.svelte
<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
75
<script>
export let data;
export let form;
</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>