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

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 — the URL of the current page
  • params — the current page’s parameters
  • route — an object with an id property representing the current route
  • status — the HTTP status code of the current page
  • error — the error object of the current page, if any (you’ll learn more about error handling in later exercises)
  • data — the data for the current page, combining the return values of all load functions
  • form — the data returned from a form action

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()}

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).

Edit this page on GitHub

1
2
3
<h1>home</h1>
<p>this is the home page.</p>