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

SvelteKit 通过 $app/state 模块提供三个只读状态对象 - pagenavigatingupdated。你最常使用的 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 page

  • params — 当前页面的 参数

    ¥params — the current page’s parameters

  • route — 具有 id 属性的对象,表示当前路由

    ¥route — an object with an id property representing the current route

  • status — 当前页面的 HTTP 状态代码

    ¥status — the HTTP status code of the current page

  • error — 当前页面的错误对象(如果有)(你将在 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 all load functions

  • form — 从 表单操作 返回的数据

    ¥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:

src/routes/+layout
<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)。

¥[!NOTE] Prior to SvelteKit 2.12, you had to use $app/stores for this, which provides a $page store with the same information. If you’re currently using $app/stores, we advise you to migrate towards $app/state (requires Svelte 5).

上一页 下一页
1
2
3
<h1>home</h1>
<p>this is the home page.</p>