跳至主要內容

$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 === nullnavigation.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 函數透過 fetchdepends 依賴於相關的 url,則會導致它們重新執行。傳回一個 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. 使用適當的選項呼叫頁面的載入函數。

這與當使用者點擊或滑鼠懸停在具有 data-sveltekit-preload-data<a> 元素時,SvelteKit 觸發的行為相同。如果下一個導航是到 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 上編輯此頁面

上一個 下一個