Skip to main content
Bases de Svelte
Introduction
Réactivité
Props
Logique
Évènements
Liaisons
Classes et styles
Actions
Transitions
Svelte avancé
Réactivité avancée
Réutiliser du contenu
Mouvements
Liaisons avancées
Advanced transitions
Context API
Special elements
<script module>
Next steps
Basic SvelteKit
Introduction
Routing
Loading data
Headers and 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.

Modifier cette page sur Github

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