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

正如我们在 路由介绍 中看到的,布局是一种在不同路由之间共享 UI 和数据加载逻辑的方式。

¥As we saw in the routing introduction, layouts are a way to share UI and data loading logic between different routes.

有时使用布局而不影响路由很有用 - 例如,你可能需要 /app/account 路由进行身份验证,而 /about 页面向全世界开放。我们可以使用路由组(括号中的目录)来做到这一点。

¥Sometimes it’s useful to use layouts without affecting the route — for example, you might need your /app and /account routes to be behind authentication, while your /about page is open to the world. We can do this with a route group, which is a directory in parentheses.

通过将 account 重命名为 (authed)/account,然后将 app 重命名为 (authed)/app,创建一个 (authed) 组。

¥Create an (authed) group by renaming account to (authed)/account then renaming app to (authed)/app.

现在我们可以通过创建 src/routes/(authed)/+layout.server.js 来控制对这些路由的访问:

¥Now we can control access to these routes by creating src/routes/(authed)/+layout.server.js:

src/routes/(authed)/+layout.server
import { redirect } from '@sveltejs/kit';

export function load({ cookies, url }) {
	if (!cookies.get('logged_in')) {
		redirect(303, `/login?redirectTo=${url.pathname}`);
	}
}

如果你尝试访问这些页面,你将被重定向到 /login 路由,该路由在 src/routes/login/+page.server.js 中有一个设置 logged_in cookie 的表单操作。

¥If you try to visit these pages, you’ll be redirected to the /login route, which has a form action in src/routes/login/+page.server.js that sets the logged_in cookie.

我们还可以通过添加 src/routes/(authed)/+layout.svelte 文件向这两个路由添加一些 UI:

¥We can also add some UI to these two routes by adding a src/routes/(authed)/+layout.svelte file:

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

{@render children()}

<form method="POST" action="/logout">
	<button>log out</button>
</form>
<script lang="ts">
	let { children } = $props();
</script>

{@render children()}

<form method="POST" action="/logout">
	<button>log out</button>
</form>
上一页 下一页
1
2
3
4
<h1>home</h1>
 
<p>this is the home page.</p>