Skip to main content
Svelte基础
介绍
响应
属性Props
逻辑表达式
事件
绑定
Classes和样式
动作Actions
转场
Svelte高阶
响应式进阶
内容复用
动画
高级绑定
高级转场
上下文API
特殊元素
脚本模块
接下来
SvelteKit基础
介绍
路由
加载数据
Headers和cookies
Shared modules
Forms
API routes
$app/state
Errors and redirects
Advanced SvelteKit
Hooks
Page options
Link options
Advanced routing
Advanced loading
Environment variables
Conclusion

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.

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

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 };
}

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 };
}

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.

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 };
}

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.

Edit this page on GitHub

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