正如我们在 布局数据 简介中看到的,+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
:
export function load() {
return { a: 1 };
}
然后,在 src/routes/sum/+layout.js
中获取该数据:
¥Then, get that data in src/routes/sum/+layout.js
:
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 serverload
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:
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 canfetch
other data that is not dependent on parent data, do that first.
<p>if a = 1 and b = a + 1, what is a + b?</p>
<a href="/sum">show answer</a>