你还可以添加改变数据的处理程序,例如 POST
。在大多数情况下,你应该改用 表单操作 — 你最终会编写更少的代码,并且它可以在没有 JavaScript 的情况下工作,从而使其更具弹性。
¥You can also add handlers that mutate data, such as POST
. In most cases, you should use form actions instead — you’ll end up writing less code, and it’ll work without JavaScript, making it more resilient.
在 ‘添加待办事项’ <input>
的 keydown
事件处理程序中,让我们将一些数据发布到服务器:
¥Inside the keydown
event handler of the ‘add a todo’ <input>
, let’s post some data to the server:
<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 = '';
}}
/>
在这里,我们将一些 JSON 发布到 /todo
API 路由 — 使用来自用户 cookie 的 userid
— 并接收新创建的待办事项的 id
作为响应。
¥Here, we’re posting some JSON to the /todo
API route — using a userid
from the user’s cookies — and receiving the id
of the newly created todo in response.
通过添加带有 POST
处理程序的 src/routes/todo/+server.js
文件来创建 /todo
路由,该处理程序在 src/lib/server/database.js
中调用 createTodo
:
¥Create the /todo
route by adding a src/routes/todo/+server.js
file with a POST
handler that calls createTodo
in src/lib/server/database.js
:
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
函数和表单操作一样,request
是一个标准的 请求 对象;await request.json()
返回我们从事件处理程序发布的数据。
¥As with load
functions and form actions, the request
is a standard Request object; await request.json()
returns the data that we posted from the event handler.
我们返回一个带有 201 已创建 状态和数据库中新生成的待办事项的 id
的响应。回到事件处理程序中,我们可以使用它来更新页面:
¥We’re returning a response with a 201 Created status and the id
of the newly generated todo in our database. Back in the event handler, we can use this to update the 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();
const todos = [...data.todos, {
id,
description
}];
data = { ...data, todos };
input.value = '';
}}
/>
你只能以这样的方式更新
data
,即通过重新加载页面获得相同的结果。data
prop 不是深度响应式的,因此你需要替换它 - 像data.todos = todos
这样的突变不会导致重新渲染。¥[!NOTE] You should only update
data
in such a way that you’d get the same result by reloading the page. Thedata
prop is not deeply reactive, so you need to replace it — mutations likedata.todos = todos
will not cause a re-render.
<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
}}
/>
<span>{todo.description}</span>
<button
aria-label="Mark as complete"
onclick={async (e) => {
// TODO handle delete
}}
></button>
</label>
</li>
{/each}
</ul>
</div>
<style>
.centered {
max-width: 20em;
margin: 0 auto;
}
label {
display: flex;
width: 100%;
}
input[type="text"] {
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;
}
</style>