正如我们在路由简介中看到的,布局是用于在不同路由之间共享 UI 和数据加载逻辑的一种方式。
有时使用布局而不影响路由会很有用——例如,你可能需要你的/app和/account路由位于身份验证之后,而你的/about页面则对所有人开放。我们可以使用路由组来实现这一点,路由组是在括号中的目录。
通过将account重命名为(authed)/account,然后将app重命名为(authed)/app来创建一个(authed)组。
现在我们可以通过创建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。
我们还可以通过添加一个src/routes/(authed)/+layout.svelte文件为这两个路由添加一些 UI
src/routes/(authed)/+layout
<script>
let { children } = $props();
</script>
<form method="POST" action="/logout">
<button>log out</button>
</form>1
2
3
4
<h1>home</h1>
<p>this is the home page.</p>