跳至主要内容

$app/navigation

import {
	function afterNavigate(callback: (navigation: import("@sveltejs/kit").AfterNavigate) => void): void

A lifecycle function that runs the supplied callback when the current component mounts, and also whenever we navigate to a new URL.

afterNavigate must be called during a component initialization. It remains active as long as the component is mounted.

afterNavigate
,
function beforeNavigate(callback: (navigation: import("@sveltejs/kit").BeforeNavigate) => void): void

A navigation interceptor that triggers before we navigate to a new URL, whether by clicking a link, calling goto(...), or using the browser back/forward controls.

Calling cancel() will prevent the navigation from completing. If navigation.type === 'leave' — meaning the user is navigating away from the app (or closing the tab) — calling cancel will trigger the native browser unload confirmation dialog. In this case, the navigation may or may not be cancelled depending on the user’s response.

When a navigation isn’t to a SvelteKit-owned route (and therefore controlled by SvelteKit’s client-side router), navigation.to.route.id will be null.

If the navigation will (if not cancelled) cause the document to unload — in other words 'leave' navigations and 'link' navigations where navigation.to.route === nullnavigation.willUnload is true.

beforeNavigate must be called during a component initialization. It remains active as long as the component is mounted.

beforeNavigate
,
function disableScrollHandling(): void

If called when the page is being updated following a navigation (in onMount or afterNavigate or an action, for example), this disables SvelteKit’s built-in scroll handling. This is generally discouraged, since it breaks user expectations.

disableScrollHandling
,
function goto(url: string | URL, opts?: {
    replaceState?: boolean | undefined;
    noScroll?: boolean | undefined;
    keepFocus?: boolean | undefined;
    invalidateAll?: boolean | undefined;
    state?: App.PageState | undefined;
} | undefined): Promise<void>

Returns a Promise that resolves when SvelteKit navigates (or fails to navigate, in which case the promise rejects) to the specified url. For external URLs, use window.location = url instead of calling goto(url).

@paramurl Where to navigate to. Note that if you've set config.kit.paths.base and the URL is root-relative, you need to prepend the base path if you want to navigate within the app.
@paramopts Options related to the navigation
goto
,
function invalidate(resource: string | URL | ((url: URL) => boolean)): Promise<void>

Causes any load functions belonging to the currently active page to re-run if they depend on the url in question, via fetch or depends. Returns a Promise that resolves when the page is subsequently updated.

If the argument is given as a string or URL, it must resolve to the same URL that was passed to fetch or depends (including query parameters). To create a custom identifier, use a string beginning with [a-z]+: (e.g. custom:state) — this is a valid URL.

The function argument can be used define a custom predicate. It receives the full URL and causes load to rerun if true is returned. This can be useful if you want to invalidate based on a pattern instead of a exact match.

// Example: Match '/path' regardless of the query parameters
import { invalidate } from '$app/navigation';

invalidate((url) => url.pathname === '/path');
@paramresource The invalidated URL
invalidate
,
function invalidateAll(): Promise<void>

Causes all load functions belonging to the currently active page to re-run. Returns a Promise that resolves when the page is subsequently updated.

invalidateAll
,
function onNavigate(callback: (navigation: import("@sveltejs/kit").OnNavigate) => MaybePromise<void | (() => void)>): void

A lifecycle function that runs the supplied callback immediately before we navigate to a new URL except during full-page navigations.

If you return a Promise, SvelteKit will wait for it to resolve before completing the navigation. This allows you to — for example — use document.startViewTransition. Avoid promises that are slow to resolve, since navigation will appear stalled to the user.

If a function (or a Promise that resolves to a function) is returned from the callback, it will be called once the DOM has updated.

onNavigate must be called during a component initialization. It remains active as long as the component is mounted.

onNavigate
,
function preloadCode(pathname: string): Promise<void>

Programmatically imports the code for routes that haven’t yet been fetched. Typically, you might call this to speed up subsequent navigation.

You can specify routes by any matching pathname such as /about (to match src/routes/about/+page.svelte) or /blog/* (to match src/routes/blog/[slug]/+page.svelte).

Unlike preloadData, this won’t call load functions. Returns a Promise that resolves when the modules have been imported.

preloadCode
,
function preloadData(href: string): Promise<{
    type: "loaded";
    status: number;
    data: Record<string, any>;
} | {
    type: "redirect";
    location: string;
}>

Programmatically preloads the given page, which means

  1. ensuring that the code for the page is loaded, and
  2. calling the page’s load function with the appropriate options.

This is the same behaviour that SvelteKit triggers when the user taps or mouses over an &#x3C;a> element with data-sveltekit-preload-data. If the next navigation is to href, the values returned from load will be used, making navigation instantaneous. Returns a Promise that resolves with the result of running the new route’s load functions once the preload is complete.

@paramhref Page to preload
preloadData
,
function pushState(url: string | URL, state: App.PageState): void

Programmatically create a new history entry with the given $page.state. To use the current URL, you can pass '' as the first argument. Used for shallow routing.

pushState
,
function replaceState(url: string | URL, state: App.PageState): void

Programmatically replace the current history entry with the given $page.state. To use the current URL, you can pass '' as the first argument. Used for shallow routing.

replaceState
} from '$app/navigation';

afterNavigate

当当前组件挂载时,以及每次导航到新 URL 时,运行提供的 callback 的生命周期函数。

afterNavigate 必须在组件初始化期间调用。只要组件已挂载,它就会保持活动状态。

function afterNavigate(
	callback: (
		navigation: import('@sveltejs/kit').AfterNavigate
	) => void
): void;

beforeNavigate

一个导航拦截器,在我们导航到新 URL 之前触发,无论是通过点击链接、调用 goto(...) 还是使用浏览器后退/前进控件。

调用 cancel() 将阻止导航完成。如果 navigation.type === 'leave'——表示用户正在离开应用(或关闭选项卡)——调用 cancel 将触发本机浏览器的卸载确认对话框。在这种情况下,导航可能会或可能不会根据用户的响应而取消。

当导航不是到 SvelteKit 拥有的路由(因此由 SvelteKit 的客户端路由器控制)时,navigation.to.route.id 将为 null

如果导航将(如果未取消)导致文档卸载——换句话说,'leave' 导航和 'link' 导航,其中 navigation.to.route === null——navigation.willUnloadtrue

beforeNavigate 必须在组件初始化期间调用。只要组件已挂载,它就会保持活动状态。

function beforeNavigate(
	callback: (
		navigation: import('@sveltejs/kit').BeforeNavigate
	) => void
): void;

disableScrollHandling

如果在导航后页面正在更新时调用(例如在 onMountafterNavigate 或操作中),这将禁用 SvelteKit 的内置滚动处理。这通常不建议这样做,因为它违反了用户的期望。

function disableScrollHandling(): void;

goto

返回一个 Promise,当 SvelteKit 导航(或无法导航,在这种情况下 Promise 拒绝)到指定的 url 时解析。对于外部 URL,请使用 window.location = url 而不是调用 goto(url)

function goto(
	url: string | URL,
	opts?:
		| {
				replaceState?: boolean | undefined;
				noScroll?: boolean | undefined;
				keepFocus?: boolean | undefined;
				invalidateAll?: boolean | undefined;
				state?: App.PageState | undefined;
		  }
		| undefined
): Promise<void>;

invalidate

如果当前活动页面的 load 函数依赖于相关 url(通过 fetchdepends),则会导致这些函数重新运行。返回一个 Promise,当页面随后更新时解析。

如果参数作为 stringURL 给出,它必须解析为传递给 fetchdepends 的相同 URL(包括查询参数)。要创建自定义标识符,请使用以 [a-z]+: 开头的字符串(例如 custom:state)——这是一个有效的 URL。

function 参数可用于定义自定义谓词。它接收完整的 URL,如果返回 true,则导致 load 重新运行。如果您想根据模式而不是精确匹配进行失效,这将非常有用。

// Example: Match '/path' regardless of the query parameters
import { function invalidate(resource: string | URL | ((url: URL) => boolean)): Promise<void>

Causes any load functions belonging to the currently active page to re-run if they depend on the url in question, via fetch or depends. Returns a Promise that resolves when the page is subsequently updated.

If the argument is given as a string or URL, it must resolve to the same URL that was passed to fetch or depends (including query parameters). To create a custom identifier, use a string beginning with [a-z]+: (e.g. custom:state) — this is a valid URL.

The function argument can be used define a custom predicate. It receives the full URL and causes load to rerun if true is returned. This can be useful if you want to invalidate based on a pattern instead of a exact match.

// Example: Match '/path' regardless of the query parameters
import { invalidate } from '$app/navigation';

invalidate((url) => url.pathname === '/path');
@paramresource The invalidated URL
invalidate
} from '$app/navigation';
function invalidate(resource: string | URL | ((url: URL) => boolean)): Promise<void>

Causes any load functions belonging to the currently active page to re-run if they depend on the url in question, via fetch or depends. Returns a Promise that resolves when the page is subsequently updated.

If the argument is given as a string or URL, it must resolve to the same URL that was passed to fetch or depends (including query parameters). To create a custom identifier, use a string beginning with [a-z]+: (e.g. custom:state) — this is a valid URL.

The function argument can be used define a custom predicate. It receives the full URL and causes load to rerun if true is returned. This can be useful if you want to invalidate based on a pattern instead of a exact match.

// Example: Match '/path' regardless of the query parameters
import { invalidate } from '$app/navigation';

invalidate((url) => url.pathname === '/path');
@paramresource The invalidated URL
invalidate
((url: URLurl) => url: URLurl.URL.pathname: stringpathname === '/path');
function invalidate(
	resource: string | URL | ((url: URL) => boolean)
): Promise<void>;

invalidateAll

导致当前活动页面的所有 load 函数重新运行。返回一个 Promise,当页面随后更新时解析。

function invalidateAll(): Promise<void>;

onNavigate

一个生命周期函数,在我们导航到新 URL 之前立即运行提供的 callback,除了在全页面导航期间。

如果返回 Promise,SvelteKit 将等待它解析,然后才能完成导航。这允许您——例如——使用 document.startViewTransition。避免解析速度慢的 Promise,因为导航在用户看来会显得停滞。

如果从回调中返回一个函数(或解析为函数的 Promise),则将在 DOM 更新后立即调用它。

onNavigate 必须在组件初始化期间调用。只要组件已挂载,它就会保持活动状态。

function onNavigate(
	callback: (
		navigation: import('@sveltejs/kit').OnNavigate
	) => MaybePromise<(() => void) | void>
): void;

preloadCode

以编程方式导入尚未获取的路由的代码。通常,您可能会调用它来加快后续导航速度。

您可以通过任何匹配的路径名指定路由,例如 /about(以匹配 src/routes/about/+page.svelte)或 /blog/*(以匹配 src/routes/blog/[slug]/+page.svelte)。

preloadData 不同,这不会调用 load 函数。返回一个 Promise,当模块导入后解析。

function preloadCode(pathname: string): Promise<void>;

preloadData

以编程方式预加载给定的页面,这意味着

  1. 确保加载页面的代码,以及
  2. 使用适当的选项调用页面的 load 函数。

这与 SvelteKit 在用户点击或将鼠标悬停在具有 <a> 元素的 data-sveltekit-preload-data 上时触发的行为相同。如果下一个导航是到 href,则将使用从 load 返回的值,从而使导航变得即时。返回一个 Promise,在预加载完成后,解析为运行新路由的 load 函数的结果。

function preloadData(href: string): Promise<
	| {
			type: 'loaded';
			status: number;
			data: Record<string, any>;
	  }
	| {
			type: 'redirect';
			location: string;
	  }
>;

pushState

以编程方式使用给定的 $page.state 创建新的历史记录条目。要使用当前 URL,您可以将 '' 作为第一个参数传递。用于 浅路由

function pushState(
	url: string | URL,
	state: App.PageState
): void;

replaceState

以编程方式使用给定的 $page.state 替换当前历史记录条目。要使用当前 URL,您可以将 '' 作为第一个参数传递。用于 浅路由

function replaceState(
	url: string | URL,
	state: App.PageState
): void;

在 GitHub 上编辑此页面

上一页 下一页