跳至主要内容

命令式组件 API

在 Svelte 3 和 4 中,与组件交互的 API 与 Svelte 5 中的不同。请注意,此页面*不*适用于 Svelte 5 应用程序中的旧版模式组件。

创建组件

const const component: anycomponent = new Component(options);

客户端组件(即使用 generate: 'dom' 编译的组件(或 generate 选项未指定))是一个 JavaScript 类。

import 
type App = SvelteComponent<Record<string, any>, any, any>
const App: LegacyComponentType
App
from './App.svelte';
const const app: SvelteComponent<Record<string, any>, any, any>app = new new App(o: ComponentConstructorOptions): SvelteComponentApp({ ComponentConstructorOptions<Record<string, any>>.target: Document | Element | ShadowRoottarget: var document: Documentdocument.Document.body: HTMLElement

Specifies the beginning and end of the document body.

MDN Reference

body
,
ComponentConstructorOptions<Record<string, any>>.props?: Record<string, any> | undefinedprops: { // assuming App.svelte contains something like // `export let answer`: answer: numberanswer: 42 } });

可以提供以下初始化选项

选项 默认值 描述
target 要渲染到的 HTMLElementShadowRoot。此选项是必需的
anchor null target 的子元素,用于在渲染组件之前立即渲染
props {} 要提供给组件的属性对象
context new Map() 要提供给组件的根级上下文键值对的 Map
hydrate false 请参阅下文
intro false 如果为 true,将在初始渲染时播放过渡,而不是等待后续状态更改

target 的现有子元素保留在原位。

hydrate 选项指示 Svelte 升级现有的 DOM(通常来自服务器端渲染),而不是创建新元素。它仅在组件使用 hydratable: true 选项 编译时才有效。<head> 元素的水化仅在服务器端渲染代码也使用 hydratable: true 编译时才能正常工作,这会向 <head> 中的每个元素添加一个标记,以便组件知道在水化期间它负责删除哪些元素。

虽然通常会保留 target 的子元素,但 hydrate: true 会导致所有子元素被移除。因此,不能将 anchor 选项与 hydrate: true 一起使用。

现有的 DOM 不需要与组件匹配 - Svelte 会在执行过程中“修复”DOM。

index
import 
type App = SvelteComponent<Record<string, any>, any, any>
const App: LegacyComponentType
App
from './App.svelte';
const const app: SvelteComponent<Record<string, any>, any, any>app = new new App(o: ComponentConstructorOptions): SvelteComponentApp({ ComponentConstructorOptions<Record<string, any>>.target: Document | Element | ShadowRoottarget: var document: Documentdocument.ParentNode.querySelector<Element>(selectors: string): Element | null (+4 overloads)

Returns the first element that is a descendant of node that matches selectors.

MDN Reference

querySelector
('#server-rendered-html'),
ComponentConstructorOptions<Record<string, any>>.hydrate?: boolean | undefinedhydrate: true });

在 Svelte 5+ 中,请改用 mount

$set

component.$set(props);

以编程方式设置实例上的属性。component.$set({ x: 1 }) 等效于组件的 <script> 块中的 x = 1

调用此方法会为下一个微任务安排更新 - DOM *不会*同步更新。

component.$set({ answer: numberanswer: 42 });

在 Svelte 5+ 中,请改用 $state 创建组件属性并更新。

let 
let props: {
    answer: number;
}
props
=
function $state<{
    answer: number;
}>(initial: {
    answer: number;
}): {
    answer: number;
} (+1 overload)
namespace $state

Declares reactive state.

Example:

let count = $state(0);

https://svelte.js.cn/docs/svelte/$state

@paraminitial The initial value
$state
({ answer: numberanswer: 42 });
const const component: anycomponent = mount(Component, {
props: {
    answer: number;
}
props
});
// ...
let props: {
    answer: number;
}
props
.answer: numberanswer = 24;

$on

component.$on(ev, callback);

导致在组件分派 event 时调用 callback 函数。

返回一个函数,当被调用时将移除事件监听器。

const const off: anyoff = component.$on('selected', (event: anyevent) => {
	var console: Console

The console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.

The module exports two specific components:

  • A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
  • A global console instance configured to write to process.stdout and process.stderr. The global console can be used without calling require('console').

Warning: The global console object’s methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O for more information.

Example using the global console:

console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
//   Error: Whoops, something bad happened
//     at [eval]:5:15
//     at Script.runInThisContext (node:vm:132:18)
//     at Object.runInThisContext (node:vm:309:38)
//     at node:internal/process/execution:77:19
//     at [eval]-wrapper:6:22
//     at evalScript (node:internal/process/execution:76:60)
//     at node:internal/main/eval_string:23:3

const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr

Example using the Console class:

const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);

myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err

const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
@seesource
console
.Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)

Prints to stdout with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format()).

const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout

See util.format() for more information.

@sincev0.1.100
log
(event: anyevent.detail.selection);
}); const off: anyoff();

在 Svelte 5+ 中,请改用回调属性。

$destroy

component.$destroy();

从 DOM 中移除组件并触发任何 onDestroy 处理程序。

在 Svelte 5+ 中,请改用 unmount

组件属性

component.prop;
component.prop = value;

如果组件使用 accessors: true 编译,则每个实例将具有与组件的每个属性相对应的 getter 和 setter。设置值将导致*同步*更新,而不是 component.$set(...) 引起的默认异步更新。

默认情况下,accessorsfalse,除非您将其编译为自定义元素。

var console: Console

The console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.

The module exports two specific components:

  • A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
  • A global console instance configured to write to process.stdout and process.stderr. The global console can be used without calling require('console').

Warning: The global console object’s methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O for more information.

Example using the global console:

console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
//   Error: Whoops, something bad happened
//     at [eval]:5:15
//     at Script.runInThisContext (node:vm:132:18)
//     at Object.runInThisContext (node:vm:309:38)
//     at node:internal/process/execution:77:19
//     at [eval]-wrapper:6:22
//     at evalScript (node:internal/process/execution:76:60)
//     at node:internal/main/eval_string:23:3

const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr

Example using the Console class:

const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);

myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err

const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
@seesource
console
.Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)

Prints to stdout with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format()).

const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout

See util.format() for more information.

@sincev0.1.100
log
(component.count);
component.count += 1;

在 Svelte 5+ 中,此概念已过时。如果要从外部访问属性,请将其 export 出去。

服务器端组件 API

const const result: anyresult = Component.render(...)

与客户端组件不同,服务器端组件在渲染后没有生命周期 - 它们的全部工作是创建一些 HTML 和 CSS。因此,API 有所不同。

服务器端组件公开了一个 render 方法,该方法可以使用可选属性调用。它返回一个包含 headhtmlcss 属性的对象,其中 head 包含遇到的任何 <svelte:head> 元素的内容。

您可以使用 svelte/register 将 Svelte 组件直接导入 Node。

var require: NodeRequire
(id: string) => any
require
('svelte/register');
const const App: anyApp =
var require: NodeRequire
(id: string) => any
require
('./App.svelte').default;
const { const head: anyhead, const html: anyhtml, const css: anycss } = const App: anyApp.render({ answer: numberanswer: 42 });

.render() 方法接受以下参数

参数 默认值 描述
props {} 要提供给组件的属性对象
options {} 选项对象

options 对象包含以下选项

选项 默认值 描述
context new Map() 要提供给组件的根级上下文键值对的 Map
const { const head: anyhead, const html: anyhtml, const css: anycss } = App.render(
	// props
	{ answer: numberanswer: 42 },
	// options
	{
		context: Map<string, string>context: new 
var Map: MapConstructor
new <string, string>(iterable?: Iterable<readonly [string, string]> | null | undefined) => Map<string, string> (+3 overloads)
Map
([['context-key', 'context-value']])
} );

在 Svelte 5+ 中,请改用 render

在 GitHub 上编辑此页面

上一页 下一页