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

你也可以添加用于修改数据的处理程序,比如 POST。在大多数情况下,你应该使用 表单 actions 代替 — 你最终会写更少的代码,而且它在没有 JavaScript 的情况下也能工作,使其更具韧性。

在”添加待办事项” <input>keydown 事件处理程序中,让我们向服务器发送一些数据:

src/routes/+page
<input
	type="text"
	autocomplete="off"
	onkeydown={async (e) => {
		if (e.key !== 'Enter') return;

		const input = e.currentTarget;
		const description = input.value;

		const response = await fetch('/todo', {
			method: 'POST',
			body: JSON.stringify({ description }),
			headers: {
				'Content-Type': 'application/json'
			}
		});

		input.value = '';
	}}
/>

这里,我们正在向 /todo API 路由发送一些 JSON 数据 — 使用来自用户 cookies 的 userid — 并在响应中接收新创建的待办事项的 id

通过添加 src/routes/todo/+server.js 文件并创建一个调用 src/lib/server/database.jscreateTodoPOST 处理程序来创建 /todo 路由:

src/routes/todo/+server
import { json } from '@sveltejs/kit';
import * as database from '$lib/server/database.js';

export async function POST({ request, cookies }) {
	const { description } = await request.json();

	const userid = cookies.get('userid');
	const { id } = await database.createTodo({ userid, description });

	return json({ id }, { status: 201 });
}

load 函数和表单 actions 一样,request 是一个标准的 Request 对象;await request.json() 返回我们从事件处理程序发送的数据。

我们返回一个带有 201 Created 状态码的响应,以及数据库中新生成的待办事项的 id。回到事件处理程序中,我们可以使用它来更新页面:

src/routes/+page
<input
	type="text"
	autocomplete="off"
	onkeydown={async (e) => {
		if (e.key !== 'Enter') return;

		const input = e.currentTarget;
		const description = input.value;

		const response = await fetch('/todo', {
			method: 'POST',
			body: JSON.stringify({ description }),
			headers: {
				'Content-Type': 'application/json'
			}
		});

		const { id } = await response.json();

		data.todos = [...data.todos, {
			id,
			description
		}];

		input.value = '';
	}}
/>

你应该只以这样的方式修改 data:即重新加载页面时会得到相同的结果。

在 GitHub 编辑此页面

<script>
let { data } = $props();
</script>

<div class="centered">
<h1>todos</h1>

<label>
add a todo:
<input
type="text"
autocomplete="off"
onkeydown={async (e) => {
if (e.key !== 'Enter') return;

const input = e.currentTarget;
const description = input.value;
// TODO handle submit

input.value = '';
}}
/>
</label>

<ul class="todos">
{#each data.todos as todo (todo.id)}
<li>
<label>
<input
type="checkbox"
checked={todo.done}
onchange={async (e) => {
const done = e.currentTarget.checked;

// TODO handle change
booting webcontainer