Skip to main content

$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 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>

Allows you to navigate programmatically to a given route, with options such as keeping the current element focused. 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’ 导航和 navigation.to.route === null 的 ‘link’ 导航 — navigation.willUnloadtrue

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

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

disableScrollHandling

如果在导航后页面更新时调用(例如在 onMountafterNavigate 或 action 中),这将禁用 SvelteKit 的内置滚动处理。

这通常不建议使用,因为它会破坏用户的预期行为。

function disableScrollHandling(): void;

goto

允许您以编程方式导航到给定的路由,并提供诸如保持当前元素焦点等选项。

返回一个 Promise,当 SvelteKit 导航(或导航失败,在这种情况下 promise 会 reject)到指定的 url 时 resolve。

对于外部 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 函数通过 fetchdepends 依赖于相关的 url,则会导致这些函数重新运行。返回一个 Promise,在页面随后更新时 resolve。

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

function 参数可用于定义自定义谓词。它接收完整的 URL 并在返回 true 时导致 load 重新运行。

如果您想基于模式而不是精确匹配来使无效化,这很有用。

// 示例:匹配 '/path',不考虑查询参数
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,在页面随后更新时 resolve。

function invalidateAll(): Promise<void>;

onNavigate

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

如果您返回一个 Promise,SvelteKit 将等待它 resolve 后才完成导航。这允许您 — 例如 — 使用 document.startViewTransition。避免使用解析较慢的 promise,因为导航会显得停滞不前。

如果从回调返回一个函数(或 resolve 为函数的 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,在模块导入完成时 resolves。

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

preloadData

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

  1. 确保页面的代码已加载,并且
  2. 调用页面 load 函数并传入适当的选项。

这与 SvelteKit 在用户点击或将鼠标悬停在带有 data-sveltekit-preload-data<a> 元素上时触发的行为相同。 如果下一次导航是到 href,将使用从 load 返回的值,使导航变得即时。 返回一个 Promise,在预加载完成后,它将 resolve 为运行新路由的 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 编辑此页面

上一页 下一页