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

应用的不同路由通常会共享通用 UI。我们可以使用适用于同一目录中所有路由的 +layout.svelte 组件,而不必在每个 +page.svelte 组件中重复它。

¥Different routes of your app will often share common UI. Instead of repeating it in each +page.svelte component, we can use a +layout.svelte component that applies to all routes in the same directory.

在这个应用中,我们有两条路由,src/routes/+page.sveltesrc/routes/about/+page.svelte,它们包含相同的导航 UI。让我们创建一个新文件 src/routes/+layout.svelte...

¥In this app we have two routes, src/routes/+page.svelte and src/routes/about/+page.svelte, that contain the same navigation UI. Let’s create a new file, src/routes/+layout.svelte...

src/routes/
├ about/
│ └ +page.svelte
├ +layout.svelte
└ +page.svelte

...并将重复的内容从 +page.svelte 文件移动到新的 +layout.svelte 文件中。{@render children()} 标签是页面内容将被渲染的位置:

¥...and move the duplicated content from the +page.svelte files into the new +layout.svelte file. The {@render children()} tag is where the page content will be rendered:

src/routes/+layout
<script>
	let { children } = $props();
</script>

<nav>
	<a href="/">home</a>
	<a href="/about">about</a>
</nav>

{@render children()}
<script lang="ts">
	let { children } = $props();
</script>

<nav>
	<a href="/">home</a>
	<a href="/about">about</a>
</nav>

{@render children()}

+layout.svelte 文件适用于每个子路由,包括兄弟 +page.svelte(如果存在)。你可以将布局嵌套到任意深度。

¥A +layout.svelte file applies to every child route, including the sibling +page.svelte (if it exists). You can nest layouts to arbitrary depth.

上一页 下一页
1
2
3
4
5
6
7
8
<nav>
	<a href="/">home</a>
	<a href="/about">about</a>
</nav>
 
<h1>home</h1>
<p>this is the home page.</p>