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

正如我们在 布局数据 简介中看到的,+page.svelte+layout.svelte 组件可以访问从其父 load 函数返回的所有内容。

¥As we saw in the introduction to layout data, +page.svelte and +layout.svelte components have access to everything returned from their parent load functions.

有时,load 函数本身从其父级访问数据很有用。这可以通过 await parent() 完成。

¥Occasionally it’s useful for the load functions themselves to access data from their parents. This can be done with await parent().

为了展示其工作原理,我们将对来自不同 load 函数的两个数字求和。首先,从 src/routes/+layout.server.js 返回一些数据:

¥To show how it works, we’ll sum two numbers that come from different load functions. First, return some data from src/routes/+layout.server.js:

src/routes/+layout.server
export function load() {
	return { a: 1 };
}

然后,在 src/routes/sum/+layout.js 中获取该数据:

¥Then, get that data in src/routes/sum/+layout.js:

src/routes/sum/+layout
export async function load({ parent }) {
	const { a } = await parent();
	return { b: a + 1 };
}

请注意,universal load 函数可以从父服务器 load 函数获取数据。反之则不然 - 服务器加载函数只能从另一个服务器加载函数获取父数据。

¥[!NOTE] Notice that a universal load function can get data from a parent server load function. The reverse is not true — a server load function can only get parent data from another server load function.

最后,在 src/routes/sum/+page.js 中,从两个 load 函数中获取父数据:

¥Finally, in src/routes/sum/+page.js, get parent data from both load functions:

src/routes/sum/+page
export async function load({ parent }) {
	const { a, b } = await parent();
	return { c: a + b };
}

使用 await parent() 时请注意不要引入瀑布。如果你可以 fetch 其他不依赖于父数据的数据,请先执行此操作。

¥[!NOTE] Take care not to introduce waterfalls when using await parent(). If you can fetch other data that is not dependent on parent data, do that first.

1
2
3
<p>if a = 1 and b = a + 1, what is a + b?</p>
<a href="/sum">show answer</a>