In my recent app, I even do one level down, and I use on:click
to handle the POST
action of a form.
- I have a page showing all the details of a book, including the tags.
- I have a modal that pops up to ask the user to input a few tags of that book by his own.
- Then I insert any 'new' tags into the database.
I use PHP to develop the backend API. I use on:click
is because I think this saves me a lot of time. The code snippet is quite straightforward.
<Modal bind:open={popupModal} size="xs" autoclose={false} class="w-full">
<form class="flex flex-col space-y-6" method="post">
<h3 class="text-xl font-medium text-gray-900 dark:text-white p-0">
为《{book.title}》添加tag
</h3>
<Label class="space-y-2">
<span>Tags(用空格分隔)</span>
<Input type="text" name="tags" bind:value={finalTags} required />
<Input type="hidden" name="id" value={book.id} />
</Label>
<Button type="button" on:click={doPost} class="w-full1">创建新的TAG</Button>
</form>
</Modal>
And then in the doPost()
function:
async function doPost() {
const inputTags = finalTags.trim().split(" ");
const oldTags = tags;
const difference = inputTags.filter((x) => !oldTags.includes(x));
const insert = difference.join(" ");
const res = await fetch(
form_uri,
{
headers: {
"Content-Type": "application/json",
},
method: "POST",
body: JSON.stringify({
'id': book.id,
'tags': insert,
}),
}
);
const json = await res.json();
location.reload();
}
So I can refresh the page after any tags being inserted.
Just my thoughts.