我有一组 id,我想为每个 id 显示一个按钮,单击该按钮时会将 id 提交到 page.server.ts 中的操作。这应该很简单,但我绞尽脑汁想让它工作。
最小可重复示例
例子.schemas.ts
import { z } from "zod";
export const exampleSchema = z.object({
exampleId: z.string().length(24),
});
export type ExampleSchema = typeof exampleSchema;
例如-component.svelte
<script lang="ts">
import { exampleSchema, type ExampleSchema } from "./example.schema";
import {
type SuperValidated,
type Infer,
superForm,
} from "sveltekit-superforms";
import SuperDebug from 'sveltekit-superforms';
import { zodClient } from "sveltekit-superforms/adapters";
export let data: SuperValidated<Infer<ExampleSchema>>;
const form = superForm(data, {
validators: zodClient(exampleSchema),
});
const { form: formData, enhance, message } = form;
let exampleArray = ["507f1f77bcf86cd799439011","507f1f77bcf86cd799439012","507f1f77bcf86cd799439013"]
</script>
<form method="POST" action="?/exampleAction" use:enhance>
{#each exampleArray as item}
<input type="hidden" name="exampleId" value="{item}"/>
<button type="submit" >{item}</button><br />
{/each}
</form>
<SuperDebug data={formData} />
+页面.服务器.ts
import type { PageServerLoad, Actions } from "./$types";
import { superValidate } from "sveltekit-superforms";
import { exampleSchema } from "$lib/components/custom/example.schema";
import { zod } from "sveltekit-superforms/adapters";
export const load: PageServerLoad = async () => {
return {
exampleForm: await superValidate(zod(exampleSchema)),
};
};
export const actions: Actions = {
exampleAction: async ({ request }) => {
const formData = await request.formData();
const exampleId = formData.get('exampleId');
// Process the ID as needed
console.log('Submitted ID:', exampleId);
return { success: true };
}
};
+页面.svelte
<script lang="ts">
import type { PageData, ActionData } from './$types';
import Example from "$lib/components/custom/example-component.svelte";
export let data: PageData;
</script>
<Example data={data.exampleForm} />
SuperDebug 总是显示 exampleId 为空,并且验证总是失败,看起来我的操作根本没有运行。