$app/state
SvelteKit 通过 $app/state
模块提供了三个只读状态对象 — page
、navigating
和 updated
。
此模块在 2.12 版本中添加。如果您使用的是早期版本的 SvelteKit,请使用
$app/stores
。
import { const navigating: Navigation | {
from: null;
to: null;
type: null;
willUnload: null;
delta: null;
complete: null;
}
An object representing an in-progress navigation, with from
, to
, type
and (if type === 'popstate'
) delta
properties.
Values are null
when no navigation is occurring, or during server rendering.
navigating, const page: Page<Record<string, string>, string | null>
A reactive object with information about the current page, serving several use cases:
- retrieving the combined
data
of all pages/layouts anywhere in your component tree (also see loading data)
- retrieving the current value of the
form
prop anywhere in your component tree (also see form actions)
- retrieving the page state that was set through
goto
, pushState
or replaceState
(also see goto and shallow routing)
- retrieving metadata such as the URL you’re on, the current route and its parameters, and whether or not there was an error
<! file: +layout.svelte >
<script>
import { page } from '$app/state';
</script>
<p>Currently at {page.url.pathname}</p>
{#if page.error}
<span class="red">Problem detected</span>
{:else}
<span class="small">All systems operational</span>
{/if}
On the server, values can only be read during rendering (in other words not in e.g. load
functions). In the browser, the values can be read at any time.
page, const updated: {
readonly current: boolean;
check(): Promise<boolean>;
}
A reactive value that’s initially false
. If version.pollInterval
is a non-zero value, SvelteKit will poll for new versions of the app and update current
to true
when it detects one. updated.check()
will force an immediate check, regardless of polling.
updated } from '$app/state';
navigating
一个表示正在进行的导航的只读对象,具有 from
、to
、type
和(如果 type === 'popstate'
)delta
属性。
当没有导航发生时或在服务端渲染期间,这些值为 null
。
const navigating:
| import('@sveltejs/kit').Navigation
| {
from: null;
to: null;
type: null;
willUnload: null;
delta: null;
complete: null;
};
page
一个包含当前页面信息的响应式对象,用于以下几个用途:
- 在组件树的任何位置检索所有页面/布局的组合
data
(另见 加载数据) - 在组件树的任何位置检索
form
prop 的当前值(另见 表单 actions) - 检索通过
goto
、pushState
或replaceState
设置的页面状态(另见 goto 和 浅路由) - 检索元数据,如当前 URL、当前路由及其参数,以及是否发生错误
<script>
import { page } from '$app/state';
</script>
<p>当前位置 {page.url.pathname}</p>
{#if page.error}
<span class="red">检测到问题</span>
{:else}
<span class="small">所有系统正常运行</span>
{/if}
<script lang="ts">
import { page } from '$app/state';
</script>
<p>当前位置 {page.url.pathname}</p>
{#if page.error}
<span class="red">检测到问题</span>
{:else}
<span class="small">所有系统正常运行</span>
{/if}
在服务端,值只能在渲染期间读取(换句话说,不能在如 load
函数等中读取)。在浏览器中,可以随时读取这些值。
const page: import('@sveltejs/kit').Page;
updated
一个初始值为 false
的响应式只读值。如果 version.pollInterval
设置为非零值,SvelteKit 将轮询检查应用程序的新版本,当检测到新版本时,将 current
更新为 true
。无论是否轮询,updated.check()
都将强制立即检查。
const updated: {
get current(): boolean;
check(): Promise<boolean>;
};