当表单从不同的路径提交到服务器操作时,我在 Sveltekit 中加载表单操作响应数据时遇到问题。
Sveltekit 应用程序具有以下结构:
/lib
MyForm.svelte
/routes
/pageA
+page.svelte
+page.server.ts
/pageB
+page.svelte
// /routes/pageA/+page.server.ts
export const actions: Actions = {
myAction: async () => {
console.log('Form action triggered');
// Do things...
return { success: true, data: 'Result data' }
}
};
<!-- /lib/MyForm.svelte -->
<script lang="ts">
import { enhance } from '$app/forms';
import { page } from '$app/stores';
import type { SubmitFunction } from '@sveltejs/kit';
const mySubmitFunction: SubmitFunction = () => {
console.log('Form Submitted');
return async ({ update }) => {
await update();
console.log('Server has responded');
console.log($page?.form);
};
};
</script>
<form
method="POST"
action="/pageA?/myAction"
use:enhance={mySubmitFunction}
>
<button type="submit">Submit</button>
</form>
当 MyForm.svelte 导入 pageA/+page.svelte 时,一切都正确运行,并$page?.form
使用返回数据进行更新。但是,当表单导入到 pageB/+page.svelte 中时,不会返回任何表单数据 - $page?.form 仍为 null。该操作仍然在客户端和服务器端运行 - 控制台仍然记录适当的消息。
这是 Sveltekit 中的错误,还是我在这里遗漏了一些东西?
编辑 根据文档和@brunnerh的答案,更新了MyForm.svelte:
<script lang="ts">
import { enhance, applyAction } from '$app/forms';
import { goto } from '$app/navigation';
...
const mySubmitFunction: SubmitFunction = () => {
console.log('Form Submitted');
return async ({ update, result }) => {
await update();
if (result.type === 'redirect') {
await goto(result.location)
} else {
await applyAction(result);
}
console.log('Server has responded');
console.log($page?.form); // Now correctly prints form result
};
};
</script>
...