svelte
import {
class SvelteComponent<Props extends Record<string, any> = Record<string, any>, Events extends Record<string, any> = any, Slots extends Record<string, any> = any>This was the base class for Svelte components in Svelte 4. Svelte 5+ components
are completely different under the hood. For typing, use Component instead.
To instantiate components, use mount instead.
See migration guide for more info.
SvelteComponent,
class SvelteComponentTyped<Props extends Record<string, any> = Record<string, any>, Events extends Record<string, any> = any, Slots extends Record<string, any> = any>SvelteComponentTyped,
function afterUpdate(fn: () => void): voidSchedules a callback to run immediately after the component has been updated.
The first time the callback runs will be after the initial onMount.
In runes mode use $effect instead.
afterUpdate,
function beforeUpdate(fn: () => void): voidSchedules a callback to run immediately before the component is updated after any state change.
The first time the callback runs will be before the initial onMount.
In runes mode use $effect.pre instead.
beforeUpdate,
function createContext<T>(): [() => T, (context: T) => T]Returns a [get, set] pair of functions for working with context in a type-safe way.
createContext,
function createEventDispatcher<EventMap extends Record<string, any> = any>(): EventDispatcher<EventMap>Creates an event dispatcher that can be used to dispatch component events.
Event dispatchers are functions that can take two arguments: name and detail.
Component events created with createEventDispatcher create a
CustomEvent.
These events do not bubble.
The detail argument corresponds to the CustomEvent.detail
property and can contain any type of data.
The event dispatcher can be typed to narrow the allowed event names and the type of the detail argument:
const dispatch = createEventDispatcher<{
loaded: null; // does not take a detail argument
change: string; // takes a detail argument of type string, which is required
optional: number | null; // takes an optional detail argument of type number
}>();
createEventDispatcher,
function createRawSnippet<Params extends unknown[]>(fn: (...params: Getters<Params>) => {
render: () => string;
setup?: (element: Element) => void | (() => void);
}): Snippet<Params>
Create a snippet programmatically
createRawSnippet,
function flushSync<T = void>(fn?: (() => T) | undefined): TSynchronously flush any pending updates.
Returns void if no callback is provided, otherwise returns the result of calling the callback.
flushSync,
import forkfork,
function getAbortSignal(): AbortSignalReturns an AbortSignal that aborts when the current derived or effect re-runs or is destroyed.
Must be called while a derived or effect is running.
<script>
import { getAbortSignal } from 'svelte';
let { id } = $props();
async function getData(id) {
const response = await fetch(`/items/${id}`, {
signal: getAbortSignal()
});
return await response.json();
}
const data = $derived(await getData(id));
</script>
getAbortSignal,
function getAllContexts<T extends Map<any, any> = Map<any, any>>(): TRetrieves the whole context map that belongs to the closest parent component.
Must be called during component initialisation. Useful, for example, if you
programmatically create a component and want to pass the existing context to it.
getAllContexts,
function getContext<T>(key: any): TRetrieves the context that belongs to the closest parent component with the specified key.
Must be called during component initialisation.
getContext,
function hasContext(key: any): booleanChecks whether a given key has been set in the context of a parent component.
Must be called during component initialisation.
hasContext,
import hydratablehydratable,
function hydrate<Props extends Record<string, any>, Exports extends Record<string, any>>(component: ComponentType<SvelteComponent<Props>> | Component<Props, Exports, any>, options: {} extends Props ? {
target: Document | Element | ShadowRoot;
props?: Props;
events?: Record<string, (e: any) => any>;
context?: Map<any, any>;
intro?: boolean;
recover?: boolean;
} : {
target: Document | Element | ShadowRoot;
props: Props;
events?: Record<string, (e: any) => any>;
context?: Map<any, any>;
intro?: boolean;
recover?: boolean;
}): Exports
Hydrates a component on the given target and returns the exports and potentially the props (if compiled with accessors: true) of the component
hydrate,
function mount<Props extends Record<string, any>, Exports extends Record<string, any>>(component: ComponentType<SvelteComponent<Props>> | Component<Props, Exports, any>, options: MountOptions<Props>): ExportsMounts a component to the given target and returns the exports and potentially the props (if compiled with accessors: true) of the component.
Transitions will play during the initial render unless the intro option is set to false.
mount,
function onDestroy(fn: () => any): voidSchedules a callback to run immediately before the component is unmounted.
Out of onMount, beforeUpdate, afterUpdate and onDestroy, this is the
only one that runs inside a server-side component.
onDestroy,
function onMount<T>(fn: () => NotFunction<T> | Promise<NotFunction<T>> | (() => any)): voidonMount, like $effect, schedules a function to run as soon as the component has been mounted to the DOM.
Unlike $effect, the provided function only runs once.
It must be called during the component’s initialisation (but doesn’t need to live inside the component;
it can be called from an external module). If a function is returned synchronously from onMount,
it will be called when the component is unmounted.
onMount functions do not run during server-side rendering.
onMount,
function setContext<T>(key: any, context: T): TAssociates an arbitrary context object with the current component and the specified key
and returns that object. The context is then available to children of the component
(including slotted content) with getContext.
Like lifecycle functions, this must be called during component initialisation.
setContext,
function settled(): Promise<void>Returns a promise that resolves once any state changes, and asynchronous work resulting from them,
have resolved and the DOM has been updated
settled,
function tick(): Promise<void>Returns a promise that resolves once any pending state changes have been applied.
tick,
function unmount(component: Record<string, any>, options?: {
outro?: boolean;
} | undefined): Promise<void>
Unmounts a component that was previously mounted using mount or hydrate.
Since 5.13.0, if options.outro is true, transitions will play before the component is removed from the DOM.
Returns a Promise that resolves after transitions have completed if options.outro is true, or immediately otherwise (prior to 5.13.0, returns void).
import { mount, unmount } from 'svelte';
import App from './App.svelte';
const app = mount(App, { target: document.body });
// later...
unmount(app, { outro: true });
unmount,
function untrack<T>(fn: () => T): Tuntrack
} from 'svelte';SvelteComponent
这是 Svelte 4 中 Svelte 组件的基类。Svelte 5+ 组件在底层完全不同。对于输入,请改用 Component。要实例化组件,请改用 mount。有关更多信息,请参阅 迁移指南。
¥This was the base class for Svelte components in Svelte 4. Svelte 5+ components
are completely different under the hood. For typing, use Component instead.
To instantiate components, use mount instead.
See migration guide for more info.
class SvelteComponent<
Props extends Record<string, any> = Record<string, any>,
Events extends Record<string, any> = any,
Slots extends Record<string, any> = any
> {…}static element?: typeof HTMLElement;组件的自定义元素版本。仅在使用 customElement 编译器选项进行编译时才存在
¥The custom element version of the component. Only present if compiled with the customElement compiler option
[prop: string]: any;constructor(options: ComponentConstructorOptions<Properties<Props, Slots>>);已弃用 此构造函数仅在使用
asClassComponent兼容性助手时存在,这是一种权宜之计。改为使用mount进行迁移。有关更多信息,请参阅 迁移指南。¥deprecated This constructor only exists when using the
asClassComponentcompatibility helper, which is a stop-gap solution. Migrate towards usingmountinstead. See migration guide for more info.
$destroy(): void;已弃用 此方法仅在使用旧版兼容性助手之一时存在,这是一种权宜之计。有关更多信息,请参阅 迁移指南。
¥deprecated This method only exists when using one of the legacy compatibility helpers, which is a stop-gap solution. See migration guide for more info.
$on<K extends Extract<keyof Events, string>>(
type: K,
callback: (e: Events[K]) => void
): () => void;已弃用 此方法仅在使用旧版兼容性助手之一时存在,这是一种权宜之计。有关更多信息,请参阅 迁移指南。
¥deprecated This method only exists when using one of the legacy compatibility helpers, which is a stop-gap solution. See migration guide for more info.
$set(props: Partial<Props>): void;已弃用 此方法仅在使用旧版兼容性助手之一时存在,这是一种权宜之计。有关更多信息,请参阅 迁移指南。
¥deprecated This method only exists when using one of the legacy compatibility helpers, which is a stop-gap solution. See migration guide for more info.
SvelteComponentTyped
改用
Component。有关更多信息,请参阅 迁移指南。¥Use
Componentinstead. See migration guide for more information.
class SvelteComponentTyped<
Props extends Record<string, any> = Record<string, any>,
Events extends Record<string, any> = any,
Slots extends Record<string, any> = any
> extends SvelteComponent<Props, Events, Slots> {}afterUpdate
改用
$effect¥Use
$effectinstead
安排在组件更新后立即运行回调。
¥Schedules a callback to run immediately after the component has been updated.
回调第一次运行将在初始 onMount 之后。
¥The first time the callback runs will be after the initial onMount.
在符文模式下,请改用 $effect。
¥In runes mode use $effect instead.
function afterUpdate(fn: () => void): void;beforeUpdate
改用
$effect.pre¥Use
$effect.preinstead
安排回调在任何状态更改后在组件更新之前立即运行。
¥Schedules a callback to run immediately before the component is updated after any state change.
回调第一次运行将在初始 onMount 之前。
¥The first time the callback runs will be before the initial onMount.
在符文模式下,请改用 $effect.pre。
¥In runes mode use $effect.pre instead.
function beforeUpdate(fn: () => void): void;createContext
自 5.40.0 起可用
¥Available since 5.40.0
返回一对 [get, set] 函数,用于以类型安全的方式处理上下文。
¥Returns a [get, set] pair of functions for working with context in a type-safe way.
如果没有父组件调用 set,get 将抛出错误。
¥get will throw an error if no parent component called set.
function createContext<T>(): [() => T, (context: T) => T];createEventDispatcher
改用回调属性和/或
$host()符文 - 参见 迁移指南¥Use callback props and/or the
$host()rune instead — see migration guide
创建一个可用于分派 组件事件 的事件分派器。事件调度程序是可以接受两个参数的函数:name 和 detail。
¥Creates an event dispatcher that can be used to dispatch component events.
Event dispatchers are functions that can take two arguments: name and detail.
使用 createEventDispatcher 创建的组件事件会创建 CustomEvent。这些事件不影响 bubble。detail 参数对应于 CustomEvent.detail 属性,可以包含任何类型的数据。
¥Component events created with createEventDispatcher create a
CustomEvent.
These events do not bubble.
The detail argument corresponds to the CustomEvent.detail
property and can contain any type of data.
可以输入事件调度程序以缩小允许的事件名称和 detail 参数的类型:
¥The event dispatcher can be typed to narrow the allowed event names and the type of the detail argument:
const const dispatch: anydispatch = createEventDispatcher<{
loaded: nullloaded: null; // does not take a detail argument
change: stringchange: string; // takes a detail argument of type string, which is required
optional: number | nulloptional: number | null; // takes an optional detail argument of type number
}>();function createEventDispatcher<
EventMap extends Record<string, any> = any
>(): EventDispatcher<EventMap>;createRawSnippet
以编程方式创建代码片段
¥Create a snippet programmatically
function createRawSnippet<Params extends unknown[]>(
fn: (...params: Getters<Params>) => {
render: () => string;
setup?: (element: Element) => void | (() => void);
}
): Snippet<Params>;flushSync
同步刷新任何待处理的更新。如果未提供回调,则返回 void,否则返回调用回调的结果。
¥Synchronously flush any pending updates. Returns void if no callback is provided, otherwise returns the result of calling the callback.
function flushSync<T = void>(fn?: (() => T) | undefined): T;fork
自 5.42 起可用
¥Available since 5.42
创建一个 ‘fork’,其中状态变化会被评估,但不会应用到 DOM。这在你怀疑用户即将执行某些操作时推测性地加载数据(例如)时非常有用。
¥Creates a ‘fork’, in which state changes are evaluated but not applied to the DOM. This is useful for speculatively loading data (for example) when you suspect that the user is about to take some action.
像 SvelteKit 这样的框架可以使用它来在用户触摸或悬停在链接上时预加载数据,使任何后续导航都感觉即时。
¥Frameworks like SvelteKit can use this to preload data when the user touches or hovers over a link, making any subsequent navigation feel instantaneous.
fn 参数是一个修改某些状态的同步函数。状态更改将在分叉初始化后恢复,然后在分叉最终提交时重新应用。
¥The fn parameter is a synchronous function that modifies some state. The
state changes will be reverted after the fork is initialised, then reapplied
if and when the fork is eventually committed.
当很明显某个 fork 不会被提交时(例如,因为用户导航到了其他地方),必须将其丢弃以避免内存泄漏。
¥When it becomes clear that a fork will not be committed (e.g. because the user navigated elsewhere), it must be discarded to avoid leaking memory.
function fork(fn: () => void): Fork;getAbortSignal
返回一个 AbortSignal,当当前 derived 或 effect 重新运行或被销毁时,该 AbortSignal 会中止。
¥Returns an AbortSignal that aborts when the current derived or effect re-runs or is destroyed.
必须在派生或效果运行时调用。
¥Must be called while a derived or effect is running.
<script>
import { getAbortSignal } from 'svelte';
let { id } = $props();
async function getData(id) {
const response = await fetch(`/items/${id}`, {
signal: getAbortSignal()
});
return await response.json();
}
const data = $derived(await getData(id));
</script>function getAbortSignal(): AbortSignal;getAllContexts
检索属于最近父组件的整个上下文映射。必须在组件初始化期间调用。例如,如果你以编程方式创建组件并希望将现有上下文传递给它,则很有用。
¥Retrieves the whole context map that belongs to the closest parent component. Must be called during component initialisation. Useful, for example, if you programmatically create a component and want to pass the existing context to it.
function getAllContexts<
T extends Map<any, any> = Map<any, any>
>(): T;getContext
检索属于指定 key 的最近父组件的上下文。必须在组件初始化期间调用。
¥Retrieves the context that belongs to the closest parent component with the specified key.
Must be called during component initialisation.
createContext 是一个类型安全的替代方案。
¥createContext is a type-safe alternative.
function getContext<T>(key: any): T;hasContext
检查给定的 key 是否已在父组件的上下文中设置。必须在组件初始化期间调用。
¥Checks whether a given key has been set in the context of a parent component.
Must be called during component initialisation.
function hasContext(key: any): boolean;hydratable
function hydratable<T>(key: string, fn: () => T): T;hydrate
在给定目标上填充组件并返回组件的导出和可能的 props(如果使用 accessors: true 编译)
¥Hydrates a component on the given target and returns the exports and potentially the props (if compiled with accessors: true) of the component
function hydrate<
Props extends Record<string, any>,
Exports extends Record<string, any>
>(
component:
| ComponentType<SvelteComponent<Props>>
| Component<Props, Exports, any>,
options: {} extends Props
? {
target: Document | Element | ShadowRoot;
props?: Props;
events?: Record<string, (e: any) => any>;
context?: Map<any, any>;
intro?: boolean;
recover?: boolean;
}
: {
target: Document | Element | ShadowRoot;
props: Props;
events?: Record<string, (e: any) => any>;
context?: Map<any, any>;
intro?: boolean;
recover?: boolean;
}
): Exports;mount
将组件挂载到给定的目标,并返回组件的导出数据以及可能的 props(如果使用 accessors: true 编译)。除非将 intro 选项设置为 false,否则初始渲染期间将播放过渡效果。
¥Mounts a component to the given target and returns the exports and potentially the props (if compiled with accessors: true) of the component.
Transitions will play during the initial render unless the intro option is set to false.
function mount<
Props extends Record<string, any>,
Exports extends Record<string, any>
>(
component:
| ComponentType<SvelteComponent<Props>>
| Component<Props, Exports, any>,
options: MountOptions<Props>
): Exports;onDestroy
安排回调在组件卸载之前立即运行。
¥Schedules a callback to run immediately before the component is unmounted.
在 onMount、beforeUpdate、afterUpdate 和 onDestroy 中,这是唯一在服务器端组件内运行的。
¥Out of onMount, beforeUpdate, afterUpdate and onDestroy, this is the
only one that runs inside a server-side component.
function onDestroy(fn: () => any): void;onMount
onMount 与 $effect 一样,安排一个函数在组件安装到 DOM 后立即运行。与 $effect 不同,提供的函数只运行一次。
¥onMount, like $effect, schedules a function to run as soon as the component has been mounted to the DOM.
Unlike $effect, the provided function only runs once.
它必须在组件初始化期间调用(但不需要位于组件内部;可以从外部模块调用它)。如果从 onMount 同步返回一个函数,则在卸载组件时将调用该函数。
¥It must be called during the component’s initialisation (but doesn’t need to live inside the component;
it can be called from an external module). If a function is returned synchronously from onMount,
it will be called when the component is unmounted.
onMount 函数在 服务器端渲染 期间不运行。
¥onMount functions do not run during server-side rendering.
function onMount<T>(
fn: () =>
| NotFunction<T>
| Promise<NotFunction<T>>
| (() => any)
): void;setContext
将任意 context 对象与当前组件和指定的 key 关联并返回该对象。然后,上下文可供具有 getContext 的组件的子项(包括插槽内容)使用。
¥Associates an arbitrary context object with the current component and the specified key
and returns that object. The context is then available to children of the component
(including slotted content) with getContext.
与生命周期函数一样,必须在组件初始化期间调用此函数。
¥Like lifecycle functions, this must be called during component initialisation.
createContext 是一个类型安全的替代方案。
¥createContext is a type-safe alternative.
function setContext<T>(key: any, context: T): T;settled
自 5.36 起可用
¥Available since 5.36
返回一个 Promise,该 Promise 会在状态发生改变、以及由此产生的异步工作完成解析并更新 DOM 后解析。
¥Returns a promise that resolves once any state changes, and asynchronous work resulting from them, have resolved and the DOM has been updated
function settled(): Promise<void>;tick
返回一个 promise,一旦应用了任何待处理的状态更改,该 promise 就会解析。
¥Returns a promise that resolves once any pending state changes have been applied.
function tick(): Promise<void>;unmount
卸载之前使用 mount 或 hydrate 安装的组件。
¥Unmounts a component that was previously mounted using mount or hydrate.
自 5.13.0 起,如果 options.outro 是 true,则 transitions 将在组件从 DOM 中移除之前播放。
¥Since 5.13.0, if options.outro is true, transitions will play before the component is removed from the DOM.
如果 options.outro 为真,则返回转换完成后解析的 Promise,否则立即解析(在 5.13.0 之前,返回 void)。
¥Returns a Promise that resolves after transitions have completed if options.outro is true, or immediately otherwise (prior to 5.13.0, returns void).
import { function mount<Props extends Record<string, any>, Exports extends Record<string, any>>(component: ComponentType<SvelteComponent<Props>> | Component<Props, Exports, any>, options: MountOptions<Props>): ExportsMounts a component to the given target and returns the exports and potentially the props (if compiled with accessors: true) of the component.
Transitions will play during the initial render unless the intro option is set to false.
mount, function unmount(component: Record<string, any>, options?: {
outro?: boolean;
} | undefined): Promise<void>
Unmounts a component that was previously mounted using mount or hydrate.
Since 5.13.0, if options.outro is true, transitions will play before the component is removed from the DOM.
Returns a Promise that resolves after transitions have completed if options.outro is true, or immediately otherwise (prior to 5.13.0, returns void).
import { mount, unmount } from 'svelte';
import App from './App.svelte';
const app = mount(App, { target: document.body });
// later...
unmount(app, { outro: true });
unmount } from 'svelte';
import type App = SvelteComponent<Record<string, any>, any, any>
const App: LegacyComponentType
App from './App.svelte';
const const app: {
$on?(type: string, callback: (e: any) => void): () => void;
$set?(props: Partial<Record<string, any>>): void;
} & Record<string, any>
app = mount<Record<string, any>, {
$on?(type: string, callback: (e: any) => void): () => void;
$set?(props: Partial<Record<string, any>>): void;
} & Record<...>>(component: ComponentType<...> | Component<...>, options: MountOptions<...>): {
$on?(type: string, callback: (e: any) => void): () => void;
$set?(props: Partial<Record<string, any>>): void;
} & Record<...>
Mounts a component to the given target and returns the exports and potentially the props (if compiled with accessors: true) of the component.
Transitions will play during the initial render unless the intro option is set to false.
mount(const App: LegacyComponentTypeApp, { target: Document | Element | ShadowRootTarget element where the component will be mounted.
target: var document: Documentdocument.Document.body: HTMLElementSpecifies the beginning and end of the document body.
body });
// later...
function unmount(component: Record<string, any>, options?: {
outro?: boolean;
} | undefined): Promise<void>
Unmounts a component that was previously mounted using mount or hydrate.
Since 5.13.0, if options.outro is true, transitions will play before the component is removed from the DOM.
Returns a Promise that resolves after transitions have completed if options.outro is true, or immediately otherwise (prior to 5.13.0, returns void).
import { mount, unmount } from 'svelte';
import App from './App.svelte';
const app = mount(App, { target: document.body });
// later...
unmount(app, { outro: true });
unmount(const app: {
$on?(type: string, callback: (e: any) => void): () => void;
$set?(props: Partial<Record<string, any>>): void;
} & Record<string, any>
app, { outro?: boolean | undefinedoutro: true });function unmount(
component: Record<string, any>,
options?:
| {
outro?: boolean;
}
| undefined
): Promise<void>;untrack
当在 $derived 或 $effect 内部使用时,在 fn 内部读取的任何状态都不会被视为依赖。
¥When used inside a $derived or $effect,
any state read inside fn will not be treated as a dependency.
function $effect(fn: () => void | (() => void)): void
namespace $effect
Runs code when a component is mounted to the DOM, and then whenever its dependencies change, i.e. $state or $derived values.
The timing of the execution is after the DOM has been updated.
Example:
$effect(() => console.log('The count is now ' + count));
If you return a function from the effect, it will be called right before the effect is run again, or when the component is unmounted.
Does not run during server-side rendering.
$effect(() => {
// this will run when `data` changes, but not when `time` changes
save(data, {
timestamp: anytimestamp: untrack(() => time)
});
});function untrack<T>(fn: () => T): T;组件(Component)
¥Component
可用于创建强类型的 Svelte 组件。
¥Can be used to create strongly typed Svelte components.
示例:(Example:)
¥Example:
你在 npm 上有一个名为 component-library 的组件库,你可以从中导出一个名为 MyComponent 的组件。对于 Svelte+TypeScript 用户,你需要提供类型。因此,你创建一个 index.d.ts:
¥You have component library on npm called component-library, from which
you export a component called MyComponent. For Svelte+TypeScript users,
you want to provide typings. Therefore you create a index.d.ts:
import type { interface Component<Props extends Record<string, any> = {}, Exports extends Record<string, any> = {}, Bindings extends keyof Props | "" = string>Can be used to create strongly typed Svelte components.
Example:
You have component library on npm called component-library, from which
you export a component called MyComponent. For Svelte+TypeScript users,
you want to provide typings. Therefore you create a index.d.ts:
import type { Component } from 'svelte';
export declare const MyComponent: Component<{ foo: string }> {}
Typing this makes it possible for IDEs like VS Code with the Svelte extension
to provide intellisense and to use the component like this in a Svelte file
with TypeScript:
<script lang="ts">
import { MyComponent } from "component-library";
</script>
<MyComponent foo={'bar'} />
Component } from 'svelte';
export declare const const MyComponent: Component<{
foo: string;
}, {}, string>
MyComponent: interface Component<Props extends Record<string, any> = {}, Exports extends Record<string, any> = {}, Bindings extends keyof Props | "" = string>Can be used to create strongly typed Svelte components.
Example:
You have component library on npm called component-library, from which
you export a component called MyComponent. For Svelte+TypeScript users,
you want to provide typings. Therefore you create a index.d.ts:
import type { Component } from 'svelte';
export declare const MyComponent: Component<{ foo: string }> {}
Typing this makes it possible for IDEs like VS Code with the Svelte extension
to provide intellisense and to use the component like this in a Svelte file
with TypeScript:
<script lang="ts">
import { MyComponent } from "component-library";
</script>
<MyComponent foo={'bar'} />
Component<{ foo: stringfoo: string }> {}输入此内容使带有 Svelte 扩展的 IDE(如 VS Code)能够提供智能感知,并在带有 TypeScript 的 Svelte 文件中像这样使用组件:
¥Typing this makes it possible for IDEs like VS Code with the Svelte extension to provide intellisense and to use the component like this in a Svelte file with TypeScript:
<script lang="ts">
import { MyComponent } from "component-library";
</script>
<MyComponent foo={'bar'} />interface Component<
Props extends Record<string, any> = {},
Exports extends Record<string, any> = {},
Bindings extends keyof Props | '' = string
> {…}(
this: void,
internals: ComponentInternals,
props: Props
): {
/**
* @deprecated This method only exists when using one of the legacy compatibility helpers, which
* is a stop-gap solution. See [migration guide](https://svelte.nodejs.cn/docs/svelte/v5-migration-guide#Components-are-no-longer-classes)
* for more info.
*/
$on?(type: string, callback: (e: any) => void): () => void;
/**
* @deprecated This method only exists when using one of the legacy compatibility helpers, which
* is a stop-gap solution. See [migration guide](https://svelte.nodejs.cn/docs/svelte/v5-migration-guide#Components-are-no-longer-classes)
* for more info.
*/
$set?(props: Partial<Props>): void;
} & Exports;internalSvelte 使用的内部对象。不要使用或修改。¥
internalAn internal object used by Svelte. Do not use or modify.props传递给组件的 props。¥
propsThe props passed to the component.
element?: typeof HTMLElement;组件的自定义元素版本。仅在使用 customElement 编译器选项进行编译时才存在
¥The custom element version of the component. Only present if compiled with the customElement compiler option
ComponentConstructorOptions
在 Svelte 4 中,组件是类。在 Svelte 5 中,它们是函数。改用
mount来实例化组件。有关更多信息,请参阅 迁移指南。¥In Svelte 4, components are classes. In Svelte 5, they are functions. Use
mountinstead to instantiate components. See migration guide for more info.
interface ComponentConstructorOptions<
Props extends Record<string, any> = Record<string, any>
> {…}target: Element | Document | ShadowRoot;anchor?: Element;props?: Props;context?: Map<any, any>;hydrate?: boolean;intro?: boolean;recover?: boolean;sync?: boolean;idPrefix?: string;$$inline?: boolean;ComponentEvents
新的
Component类型没有专用的事件类型。改用ComponentProps。¥The new
Componenttype does not have a dedicated Events type. UseComponentPropsinstead.
type ComponentEvents<Comp extends SvelteComponent> =
Comp extends SvelteComponent<any, infer Events>
? Events
: never;ComponentInternals
不同环境之间的内部实现细节不同
¥Internal implementation details that vary between environments
type ComponentInternals = Branded<{}, 'ComponentInternals'>;ComponentProps
便利类型,用于获取给定组件所需的属性。
¥Convenience type to get the props the given component expects.
示例:确保变量包含 MyComponent 所需的 props:
¥Example: Ensure a variable contains the props expected by MyComponent:
import type { type ComponentProps<Comp extends SvelteComponent | Component<any, any>> = Comp extends SvelteComponent<infer Props extends Record<string, any>, any, any> ? Props : Comp extends Component<infer Props extends Record<...>, any, string> ? Props : neverConvenience type to get the props the given component expects.
Example: Ensure a variable contains the props expected by MyComponent:
import type { ComponentProps } from 'svelte';
import MyComponent from './MyComponent.svelte';
// Errors if these aren't the correct props expected by MyComponent.
const props: ComponentProps<typeof MyComponent> = { foo: 'bar' };
In Svelte 4, you would do ComponentProps<MyComponent> because MyComponent was a class.
Example: A generic function that accepts some component and infers the type of its props:
import type { Component, ComponentProps } from 'svelte';
import MyComponent from './MyComponent.svelte';
function withProps<TComponent extends Component<any>>(
component: TComponent,
props: ComponentProps<TComponent>
) {};
// Errors if the second argument is not the correct props expected by the component in the first argument.
withProps(MyComponent, { foo: 'bar' });
ComponentProps } from 'svelte';
import type MyComponent = SvelteComponent<Record<string, any>, any, any>
const MyComponent: LegacyComponentType
MyComponent from './MyComponent.svelte';
// Errors if these aren't the correct props expected by MyComponent.
const const props: Record<string, any>props: type ComponentProps<Comp extends SvelteComponent | Component<any, any>> = Comp extends SvelteComponent<infer Props extends Record<string, any>, any, any> ? Props : Comp extends Component<infer Props extends Record<...>, any, string> ? Props : neverConvenience type to get the props the given component expects.
Example: Ensure a variable contains the props expected by MyComponent:
import type { ComponentProps } from 'svelte';
import MyComponent from './MyComponent.svelte';
// Errors if these aren't the correct props expected by MyComponent.
const props: ComponentProps<typeof MyComponent> = { foo: 'bar' };
In Svelte 4, you would do ComponentProps<MyComponent> because MyComponent was a class.
Example: A generic function that accepts some component and infers the type of its props:
import type { Component, ComponentProps } from 'svelte';
import MyComponent from './MyComponent.svelte';
function withProps<TComponent extends Component<any>>(
component: TComponent,
props: ComponentProps<TComponent>
) {};
// Errors if the second argument is not the correct props expected by the component in the first argument.
withProps(MyComponent, { foo: 'bar' });
ComponentProps<typeof const MyComponent: LegacyComponentTypeMyComponent> = { foo: stringfoo: 'bar' };在 Svelte 4 中,由于
MyComponent是一个类,因此你需要使用ComponentProps<MyComponent>。
示例:接受某些组件并推断其 props 类型的通用函数:
¥Example: A generic function that accepts some component and infers the type of its props:
import type { interface Component<Props extends Record<string, any> = {}, Exports extends Record<string, any> = {}, Bindings extends keyof Props | "" = string>Can be used to create strongly typed Svelte components.
Example:
You have component library on npm called component-library, from which
you export a component called MyComponent. For Svelte+TypeScript users,
you want to provide typings. Therefore you create a index.d.ts:
import type { Component } from 'svelte';
export declare const MyComponent: Component<{ foo: string }> {}
Typing this makes it possible for IDEs like VS Code with the Svelte extension
to provide intellisense and to use the component like this in a Svelte file
with TypeScript:
<script lang="ts">
import { MyComponent } from "component-library";
</script>
<MyComponent foo={'bar'} />
Component, type ComponentProps<Comp extends SvelteComponent | Component<any, any>> = Comp extends SvelteComponent<infer Props extends Record<string, any>, any, any> ? Props : Comp extends Component<infer Props extends Record<...>, any, string> ? Props : neverConvenience type to get the props the given component expects.
Example: Ensure a variable contains the props expected by MyComponent:
import type { ComponentProps } from 'svelte';
import MyComponent from './MyComponent.svelte';
// Errors if these aren't the correct props expected by MyComponent.
const props: ComponentProps<typeof MyComponent> = { foo: 'bar' };
In Svelte 4, you would do ComponentProps<MyComponent> because MyComponent was a class.
Example: A generic function that accepts some component and infers the type of its props:
import type { Component, ComponentProps } from 'svelte';
import MyComponent from './MyComponent.svelte';
function withProps<TComponent extends Component<any>>(
component: TComponent,
props: ComponentProps<TComponent>
) {};
// Errors if the second argument is not the correct props expected by the component in the first argument.
withProps(MyComponent, { foo: 'bar' });
ComponentProps } from 'svelte';
import type MyComponent = SvelteComponent<Record<string, any>, any, any>
const MyComponent: LegacyComponentType
MyComponent from './MyComponent.svelte';
function function withProps<TComponent extends Component<any>>(component: TComponent, props: ComponentProps<TComponent>): voidwithProps<function (type parameter) TComponent in withProps<TComponent extends Component<any>>(component: TComponent, props: ComponentProps<TComponent>): voidTComponent extends interface Component<Props extends Record<string, any> = {}, Exports extends Record<string, any> = {}, Bindings extends keyof Props | "" = string>Can be used to create strongly typed Svelte components.
Example:
You have component library on npm called component-library, from which
you export a component called MyComponent. For Svelte+TypeScript users,
you want to provide typings. Therefore you create a index.d.ts:
import type { Component } from 'svelte';
export declare const MyComponent: Component<{ foo: string }> {}
Typing this makes it possible for IDEs like VS Code with the Svelte extension
to provide intellisense and to use the component like this in a Svelte file
with TypeScript:
<script lang="ts">
import { MyComponent } from "component-library";
</script>
<MyComponent foo={'bar'} />
Component<any>>(
component: TComponent extends Component<any>component: function (type parameter) TComponent in withProps<TComponent extends Component<any>>(component: TComponent, props: ComponentProps<TComponent>): voidTComponent,
props: ComponentProps<TComponent>props: type ComponentProps<Comp extends SvelteComponent | Component<any, any>> = Comp extends SvelteComponent<infer Props extends Record<string, any>, any, any> ? Props : Comp extends Component<infer Props extends Record<...>, any, string> ? Props : neverConvenience type to get the props the given component expects.
Example: Ensure a variable contains the props expected by MyComponent:
import type { ComponentProps } from 'svelte';
import MyComponent from './MyComponent.svelte';
// Errors if these aren't the correct props expected by MyComponent.
const props: ComponentProps<typeof MyComponent> = { foo: 'bar' };
In Svelte 4, you would do ComponentProps<MyComponent> because MyComponent was a class.
Example: A generic function that accepts some component and infers the type of its props:
import type { Component, ComponentProps } from 'svelte';
import MyComponent from './MyComponent.svelte';
function withProps<TComponent extends Component<any>>(
component: TComponent,
props: ComponentProps<TComponent>
) {};
// Errors if the second argument is not the correct props expected by the component in the first argument.
withProps(MyComponent, { foo: 'bar' });
ComponentProps<function (type parameter) TComponent in withProps<TComponent extends Component<any>>(component: TComponent, props: ComponentProps<TComponent>): voidTComponent>
) {};
// Errors if the second argument is not the correct props expected by the component in the first argument.
function withProps<LegacyComponentType>(component: LegacyComponentType, props: Record<string, any>): voidwithProps(const MyComponent: LegacyComponentTypeMyComponent, { foo: stringfoo: 'bar' });type ComponentProps<
Comp extends SvelteComponent | Component<any, any>
> =
Comp extends SvelteComponent<infer Props>
? Props
: Comp extends Component<infer Props, any>
? Props
: never;ComponentType
与新的
Component类型一起使用时,此类型已过时。¥This type is obsolete when working with the new
Componenttype.
type ComponentType<
Comp extends SvelteComponent = SvelteComponent
> = (new (
options: ComponentConstructorOptions<
Comp extends SvelteComponent<infer Props>
? Props
: Record<string, any>
>
) => Comp) & {
/** The custom element version of the component. Only present if compiled with the `customElement` compiler option */
element?: typeof HTMLElement;
};EventDispatcher
interface EventDispatcher<
EventMap extends Record<string, any>
> {…}<Type extends keyof EventMap>(
...args: null extends EventMap[Type]
? [type: Type, parameter?: EventMap[Type] | null | undefined, options?: DispatchOptions]
: undefined extends EventMap[Type]
? [type: Type, parameter?: EventMap[Type] | null | undefined, options?: DispatchOptions]
: [type: Type, parameter: EventMap[Type], options?: DispatchOptions]
): boolean;Fork
自 5.42 起可用
¥Available since 5.42
表示屏幕外正在发生的工作,例如为预期用户导航而预加载的数据。
¥Represents work that is happening off-screen, such as data being preloaded in anticipation of the user navigating
interface Fork {…}commit(): Promise<void>;提交 fork。一旦状态更改应用完毕,promise 将会解析。
¥Commit the fork. The promise will resolve once the state change has been applied
discard(): void;放弃 fork
¥Discard the fork
MountOptions
定义 mount() 函数接受的选项。
¥Defines the options accepted by the mount() function.
type MountOptions<
Props extends Record<string, any> = Record<string, any>
> = {
/**
* Target element where the component will be mounted.
*/
target: Document | Element | ShadowRoot;
/**
* Optional node inside `target`. When specified, it is used to render the component immediately before it.
*/
anchor?: Node;
/**
* Allows the specification of events.
* @deprecated Use callback props instead.
*/
events?: Record<string, (e: any) => any>;
/**
* Can be accessed via `getContext()` at the component level.
*/
context?: Map<any, any>;
/**
* Whether or not to play transitions on initial render.
* @default true
*/
intro?: boolean;
} & ({} extends Props
? {
/**
* Component properties.
*/
props?: Props;
}
: {
/**
* Component properties.
*/
props: Props;
});代码片段(Snippet)
¥Snippet
#snippet 块的类型。你可以使用它来(例如)表示你的组件需要某种类型的代码片段:
¥The type of a #snippet block. You can use it to (for example) express that your component expects a snippet of a certain type:
let { let banner: Snippet<[{
text: string;
}]>
banner }: { banner: Snippet<[{
text: string;
}]>
banner: type Snippet = /*unresolved*/ anySnippet<[{ text: stringtext: string }]> } = function $props(): any
namespace $props
Declares the props that a component accepts. Example:
let { optionalProp = 42, requiredProp, bindableProp = $bindable() }: { optionalProp?: number; requiredProps: string; bindableProp: boolean } = $props();
$props();你只能通过 {@render ...} 标签调用代码片段。
¥You can only call a snippet through the {@render ...} tag.
请参阅 代码片段文档 了解更多信息。
¥See the snippet documentation for more info.
interface Snippet<Parameters extends unknown[] = []> {…}(
this: void,
// this conditional allows tuples but not arrays. Arrays would indicate a
// rest parameter type, which is not supported. If rest parameters are added
// in the future, the condition can be removed.
...args: number extends Parameters['length'] ? never : Parameters
): {
'{@render ...} must be called with a Snippet': "import type { Snippet } from 'svelte'";
} & typeof SnippetReturn;