Skip to main content
Svelte 基础
介绍
响应式
属性
逻辑
事件
绑定
类和样式
Actions
过渡动画
Svelte 进阶
高级响应性
复用内容
Motion
高级绑定
高级过渡效果
Context API
特殊元素
<script module>
后续步骤
SvelteKit 基础
介绍
路由
加载数据
请求头和 Cookie
共享模块
表单
API 路由
$app/state
错误和重定向
SvelteKit 进阶
钩子函数
页面选项
链接选项
高级路由
高级加载
环境变量
结论

由于我们使用了 <form>,即使用户没有启用 JavaScript(这种情况比你想象的要常见),我们的应用也能正常工作。这很好,因为这意味着我们的应用具有良好的韧性。

大多数情况下,用户是 启用 JavaScript 的。在这些情况下,我们可以 渐进式增强 用户体验,就像 SvelteKit 通过客户端路由渐进式增强 <a> 元素一样。

$app/forms 导入 enhance 函数...

src/routes/+page
<script>
	import { enhance } from '$app/forms';

	let { data, form } = $props();
</script>
<script lang="ts">
	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>
<script lang="ts">
	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>

在 GitHub 编辑此页面

上一页 下一页
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>