SvelteKit 通过 $app/state 模块提供三个只读状态对象 - page、navigating 和 updated。你最常使用的 page 是提供有关当前页面的信息:
¥SvelteKit makes three readonly state objects available via the $app/state module — page, navigating and updated. The one you’ll use most often is page, which provides information about the current page:
url— 当前页面的 URL¥
url— the URL of the current pageparams— 当前页面的 参数¥
params— the current page’s parametersroute— 具有id属性的对象,表示当前路由¥
route— an object with anidproperty representing the current routestatus— 当前页面的 HTTP 状态代码¥
status— the HTTP status code of the current pageerror— 当前页面的错误对象(如果有)(你将在 later exercises 中了解有关错误处理的更多信息)¥
error— the error object of the current page, if any (you’ll learn more about error handling in later exercises)data— 当前页面的数据,结合所有load的返回值函数¥
data— the data for the current page, combining the return values of allloadfunctionsform— 从 表单操作 返回的数据¥
form— the data returned from a form action
这些属性中的每一个都是被动的,在后台使用 $state.raw。这是一个使用 page.url.pathname 的示例:
¥Each of these properties is reactive, using $state.raw under the hood. Here’s an example using page.url.pathname:
<script>
import { page } from '$app/state';
let { children } = $props();
</script>
<nav>
<a href="/" aria-current={page.url.pathname === '/'}>
home
</a>
<a href="/about" aria-current={page.url.pathname === '/about'}>
about
</a>
</nav>
{@render children()}<script lang="ts">
import { page } from '$app/state';
let { children } = $props();
</script>
<nav>
<a href="/" aria-current={page.url.pathname === '/'}>
home
</a>
<a href="/about" aria-current={page.url.pathname === '/about'}>
about
</a>
</nav>
{@render children()}在 SvelteKit 2.12 之前,你必须使用
$app/stores来实现此目的,它会为$page存储提供相同的信息。如果你目前正在使用$app/stores,我们建议你迁移到$app/state(需要 Svelte 5)。
<h1>home</h1>
<p>this is the home page.</p>