跳至主要內容

實際上,只有單一動作的頁面相當罕見。大多數時候,您需要在一個頁面上有多個動作。在這個應用程式中,建立一個待辦事項還不夠 — 我們希望在它們完成後將其刪除。

首先,將我們的 default 動作替換為具名的 createdelete 動作

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> 元素有一個可選的 action 屬性,它類似於 <a> 元素的 href 屬性。更新現有的表單,使其指向新的 create 動作

src/routes/+page
<form method="POST" action="?/create">
	<label>
		add a todo:
		<input
			name="description"
			autocomplete="off"
		/>
	</label>
</form>

action 屬性可以是任何 URL — 如果該動作是在另一個頁面上定義的,您可能會看到類似 /todos?/create 的內容。由於該動作是在這個頁面上,我們可以完全省略路徑名稱,因此開頭會有 ? 字元。

接下來,我們要為每個待辦事項建立一個表單,並包含一個隱藏的 <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>

在 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
<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>