在 SvelteKit 应用中,页面数据可能来自数据库、认证会话或公共接口。直接把所有请求放进组件挂载回调,会让页面导航、错误处理和数据复用变得复杂。load 函数提供明确的数据读取边界。本文使用支持 Svelte 5 的 SvelteKit 页面结构,构建工作区详情。
1. 组织页面与数据读取文件
服务端专用逻辑放进 +page.server.ts;需要在服务器和浏览器都运行的通用逻辑可放在 +page.ts。组件主要负责呈现返回的数据。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/742516d897a5e67cb7271a8f575fc6e0fe3056b4">
<main><h1>工作区详情</h1><section aria-label="工作记录"></section></main>
</div>
src/routes/workspaces/[id]/
+page.server.ts
+page.svelte
+error.svelte
2. 在 server load 中验证权限
数据库连接和私人配置只能留在服务端。读取工作区时,以服务端会话确定用户身份,并检查请求路径中的资源 ID。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/d3fbbd526808b9378d86a88f1199eafe7e855613">
<section><h2>{data.workspace.name}</h2><p>{data.workspace.description}</p></section>
</div>
import {
error } from '@sveltejs/kit';
import type {
PageServerLoad } from './$types';
export const load: PageServerLoad = async ({
params, locals }) => {
if (!locals.user) error(401, '请先登录');
const workspace = await findVisibleWorkspace(locals.user.id, params.id);
if (!workspace) error(404, '工作区不存在');
return {
workspace: toPublicWorkspace(workspace) };
};
3. 使用生成的 PageData 类型
SvelteKit 为路由生成类型。Svelte 5 组件通过 $props 读取 data,并利用类型检查避免模板访问不存在的字段。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/b3b4fcbc146dd1ed3ab4df1254f6c98582be52b3">
<article><h2>{data.workspace.name}</h2><p>{data.workspace.description}</p></article>
</div>
<script lang="ts">
import type { PageData } from './$types';
let { data }: { data: PageData } = $props();
</script>
4. 布局数据适合共享会话信息
多个子页面共同需要工作区名称、用户摘要和菜单配置时,可将通用数据移到 +layout.server.ts。返回值仍应限制为前端需要的公开字段。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/4e61fb1b816f56cbfc14d974992112e3abe20a43">
<header><strong>{data.account.displayName}</strong></header>
<nav aria-label="工作区导航">{@render children()}</nav>
</div>
新项目可以使用 Svelte 5 的 children snippet 组织布局内容。不要把完整会话 Token 或数据库记录传给客户端。
5. 在通用 load 中使用事件 fetch
通用 load 接收框架提供的 fetch,与服务器渲染及客户端导航协作。避免对本可直接读取的服务端数据库再绕行 HTTP。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/6d95e8570561277e9958e2c7218b64646f701ac4">
<ul>{#each data.publicNotices as notice (notice.id)}<li>{notice.title}</li>{/each}</ul>
</div>
import type {
PageLoad } from './$types';
export const load: PageLoad = async ({
fetch }) => {
const response = await fetch('/api/public-notices');
if (!response.ok) throw new Error('读取公告失败');
return {
publicNotices: await response.json() };
};
6. 避免无必要的父子读取瀑布
只有子级真正依赖父级数据时才调用 parent。可独立执行的请求应尽早开始,避免先等待不相关的布局数据再查询列表。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/a2f13ad1991e0f598de03b9a82da17f67f901b33">
<section><h2>工作记录</h2><RecordList items={data.records} /><NoticeList items={data.notices} /></section>
</div>
const [records, notices] = await Promise.all([
readRecords(workspaceId), readNotices(workspaceId)
]);
7. 为自定义数据建立失效标识
服务端数据变化后,需要通知页面重新读取。load 中声明 depends,可通过对应的 invalidate 精确更新依赖,而不是无条件重新加载整个应用。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/71a691dfd4be014c98dfd53761b08a06dc9174e9">
<button onclick={refresh}>刷新工作记录</button>
</div>
// load 函数中
depends('workspace:records');
// 客户端组件中
import {
invalidate } from '$app/navigation';
async function refresh() {
await invalidate('workspace:records'); }
8. 让错误页面保留有效导航
预期业务错误通过 error 声明,最近的 +error.svelte 负责对应页面的错误反馈。避免向用户展示内部异常堆栈。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/115366d0e61d87541a12f1b18745079ac292f282">
<section role="alert"><h2>无法读取工作区</h2><p>请返回工作区列表后重试。</p></section>
</div>
根布局错误与普通页面错误的边界并不完全相同。部署测试需要覆盖直接访问、导航中出错和根数据加载失败。
9. 区分数据刷新与完整页面导航
同一路由的参数变化可能复用组件实例,因此组件不能假设只在挂载时收到 data。派生展示应随 data 更新,不要将初始数据复制到不会再同步的变量。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/c87f96dedb85b409d95f44c0fadc616b09e44225">
<p>当前工作区:{data.workspace.name}</p><p>记录数:{data.records.length}</p>
</div>
<script lang="ts">
let { data } = $props();
let recordCount = $derived(data.records.length);
</script>
10. 验收真实请求和数据泄漏边界
验证登录状态、资源权限、参数变化、数据失效和网络故障。检查浏览器接收的数据是否包含不必要的私人字段,并确认快速导航不会误显示旧工作区。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/397f2296144ec139ad909ed6073bc56fc3d4e558">
<ul aria-label="数据加载验收"><li>参数变化后显示对应工作区</li><li>更新后列表及时刷新</li><li>错误页面保留恢复入口</li></ul>
</div>
总结
SvelteKit load 将数据读取与页面生命周期连接起来。通过服务端权限边界、合理的布局共享和细粒度失效机制,能够减少重复请求及组件内部的数据同步代码。