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

聪明伶俐有追求的小主应该已经注意到了src/routes/+page.sveltesrc/routes/about/+page.svelte的导航部分是一样的。 能不能只写一次让需要的页面都可以共用呢。这就是+layout.svelte会帮我们解决。我们可以把相同的部分写到+layout.svelte里,相同路由下的所有路由都会使用这个布局. 添加src/routes/+layout.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. 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

把页面中相同的部分移动到+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不但对所有下级路由有效,对同级路由也有效哦。而且可以逐级嵌套。

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

Edit this page on GitHub

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>