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 的生命周期函数。

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

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

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

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

beforeNavigate

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

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

调用 cancel() 将阻止导航完成。如果 navigation.type === 'leave' — 意味着用户正在离开应用(或关闭选项卡) — 调用 cancel 将触发原生浏览器卸载确认对话框。在这种情况下,导航可能会或可能不会被取消,具体取决于用户的响应。

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

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

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

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

¥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。只要组件已安装,它就会保持活动状态。

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

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

disableScrollHandling

如果在导航(例如,在 onMountafterNavigate 或操作中)之后更新页面时调用,则会禁用 SvelteKit 的内置滚动处理。通常不鼓励这样做,因为它打破了用户的期望。

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

function disableScrollHandling(): void;

goto

允许你以编程方式导航到给定的路由,并提供诸如保持当前元素聚焦等选项。返回一个 Promise,当 SvelteKit 导航(或导航失败,在这种情况下 promise 被拒绝)到指定的 url 时解析。

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

对于外部 URL,请使用 window.location = url,而不是调用 goto(url)

¥For external URLs, use window.location = url instead of calling goto(url).

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

invalidate

如果任何属于当前活动页面的 load 函数依赖于相关 url,则通过 fetchdepends 重新运行。返回页面随后更新时解析的 Promise

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

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

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

function 参数可用于定义自定义谓词。它接收完整的 URL,并在返回 true 时导致 load 重新运行。如果你想根据模式而不是完全匹配使无效,这将很有用。

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

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

function invalidateAll(): Promise<void>;

onNavigate

在我们导航到新 URL 之前立即运行提供的 callback 的生命周期函数(全页导航除外)。

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

如果你返回 Promise,SvelteKit 将等待它解析后再完成导航。这允许你(例如)使用 document.startViewTransition。避免解决速度慢的 promise,因为导航在用户看来会停滞不前。

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

如果回调返回一个函数(或解析为函数的 Promise),则 DOM 更新后将调用该函数。

¥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。只要组件已安装,它就会保持活动状态。

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

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

preloadCode

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

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

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

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

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

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

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

preloadData

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

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

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

¥This is the same behaviour that SvelteKit triggers when the user taps or mouses over an <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.

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

pushState

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

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

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

replaceState

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

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

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