単一のアクションしか持たないページは、実際には非常にまれです。ほとんどの場合、ページに複数のアクションが必要になります。このアプリでは、Todoを作成するだけでは十分ではありません。完了したら削除できるようにしたいと考えています。
まず、defaultアクションを、名前付きのcreateとdeleteアクションに置き換えます。
src/routes/+page.server
export const actions = {
create: async ({ cookies, request }) => {
const data = await request.formData();
db.createTodo(cookies.get('userid'), data.get('description'));
},
delete: async ({ cookies, request }) => {
const data = await request.formData();
db.deleteTodo(cookies.get('userid'), data.get('id'));
}
};デフォルトのアクションは、名前付きのアクションと共存できません。
<form>要素には、<a>要素のhref属性に似た、オプションのaction属性があります。既存のフォームを更新して、新しいcreateアクションを指すようにします。
src/routes/+page
<form method="POST" action="?/create">
<label>
add a todo:
<input
name="description"
autocomplete="off"
/>
</label>
</form>
action属性は任意のURLにできます。アクションが別のページで定義されている場合は、/todos?/createのようになる可能性があります。アクションはこのページにあるため、パス名を完全に省略できます。そのため、先頭に?文字が付いています。
次に、各Todoに対してフォームを作成し、それを一意に識別する非表示の<input>を含めます。
src/routes/+page
<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>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
<script>
let { data } = $props();</script>
<div class="centered">
<h1>todos</h1>
<form method="POST">
<label>
add a todo:
<input
name="description"
autocomplete="off"
/>
</label>
</form>
<ul class="todos">
{#each data.todos as todo (todo.id)}<li>
{todo.description}</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>