你也可以新增會變更資料的處理函式,例如 POST
。在大多數情況下,你應該改用表單動作 — 你會少寫一些程式碼,而且它可以在沒有 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 = '';
}}
/>
在這裡,我們將一些 JSON 張貼到 /todo
API 路由 — 使用使用者 Cookie 中的 userid
— 並收到回應中新建立的待辦事項的 id
。
藉由新增一個 src/routes/todo/+server.js
檔案來建立 /todo
路由,其中包含一個 POST
處理函式,該函式會呼叫 src/lib/server/database.js
中的 createTodo
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
函式和表單動作一樣,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
。
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
76
77
78
79
80
81
82
83
84
85
86
<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>