Skip to main content
基本 Svelte
介绍
反应性
属性
逻辑
事件
绑定
类和样式
动作
转换
高级 Svelte
高级反应性
重用内容
运动
高级绑定
高级转换
上下文 API
特殊元素
<script module>
后续步骤
基本 SvelteKit
介绍
路由
加载数据
标题和 cookie
共享模块
表单
API 路由
$app/state
错误和重定向
高级 SvelteKit
钩子
页面选项
链接选项
高级路由
高级加载
环境变量
结论

有时,你可能需要一起使用服务器加载函数和通用加载函数。例如,你可能需要从服务器返回数据,但还需要返回无法序列化为服务器数据的值。

¥Occasionally, you might need to use a server load function and a universal load function together. For example, you might need to return data from the server, but also return a value that can’t be serialized as server data.

在这个例子中,我们希望根据从 src/routes/+page.server.js 获得的数据是否为 ​​cool,从 load 返回不同的组件。

¥In this example we want to return a different component from load depending on whether the data we got from src/routes/+page.server.js is cool or not.

我们可以通过 data 属性访问 src/routes/+page.js 中的服务器数据:

¥We can access server data in src/routes/+page.js via the data property:

src/routes/+page
export async function load({ data }) {
	const module = data.cool
		? await import('./CoolComponent.svelte')
		: await import('./BoringComponent.svelte');

	return {
		component: module.default,
		message: data.message
	};
}

请注意,数据未合并 - 我们必须从通用 load 函数明确返回 message

¥[!NOTE] Note that the data isn’t merged — we must explicitly return message from the universal load function.

1
2
3
4
5
6
<script>
	let { data } = $props();
</script>
 
<data.component message={data.message} />