命令式组件 API
在 Svelte 3 和 4 中,与组件交互的 API 与 Svelte 5 不同。请注意,此页面不适用于 Svelte 5 应用程序中的遗留模式组件。
创建组件
const const component: any
component = 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): SvelteComponent
App({
ComponentConstructorOptions<Record<string, any>>.target: Document | Element | ShadowRoot
target: var document: Document
document.Document.body: HTMLElement
Specifies the beginning and end of the document body.
body,
ComponentConstructorOptions<Record<string, any>>.props?: Record<string, any> | undefined
props: {
// 假设 App.svelte 包含类似
// `export let answer` 的内容:
answer: number
answer: 42
}
});
可以提供以下初始化选项:
选项 | 默认值 | 描述 |
---|---|---|
target |
无 | 要渲染到的 HTMLElement 或 ShadowRoot 。此选项是必需的 |
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。
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): SvelteComponent
App({
ComponentConstructorOptions<Record<string, any>>.target: Document | Element | ShadowRoot
target: var document: Document
document.ParentNode.querySelector<Element>(selectors: string): Element | null (+4 overloads)
Returns the first element that is a descendant of node that matches selectors.
querySelector('#server-rendered-html'),
ComponentConstructorOptions<Record<string, any>>.hydrate?: boolean | undefined
hydrate: true
});
在 Svelte 5+ 中,请使用
mount
代替
$set
component.$set(props);
以编程方式在实例上设置 props。component.$set({ x: 1 })
等同于在组件的 <script>
块内的 x = 1
。
调用此方法会为下一个微任务调度更新 — DOM 不会同步更新。
component.$set({ answer: number
answer: 42 });
在 Svelte 5+ 中,使用
$state
来创建组件 props 并更新它let
props =
let props: { answer: number; }
$state({
function $state<{ answer: number; }>(initial: { answer: number; }): { answer: number; } (+1 overload) namespace $state
answer: number
answer: 42 }); constconst component: any
component = mount(Component, {props }); // ...
props: { answer: number; }
props.
let props: { answer: number; }
answer: number
answer = 24;
$on
component.$on(ev, callback);
当组件分发一个 event
时,会调用 callback
函数。
返回一个函数,调用该函数时将移除事件监听器。
const const off: any
off = component.$on('selected', (event: any
event) => {
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
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.
log(event: any
event.detail.selection);
});
const off: any
off();
在 Svelte 5+ 中,请改用回调 props
$destroy
component.$destroy();
从 DOM 中移除组件并触发任何 onDestroy
处理程序。
在 Svelte 5+ 中,请使用
unmount
代替
组件属性
component.prop;
component.prop = value;
如果组件使用 accessors: true
编译,每个实例都会有与组件的每个 prop 对应的 getter 和 setter。设置值将导致同步更新,而不是由 component.$set(...)
导致的默认异步更新。
默认情况下,accessors
为 false
,除非你将其编译为自定义元素。
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
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.
log(component.count);
component.count += 1;
在 Svelte 5+ 中,此概念已过时。如果你想让属性从外部访问,请使用
export
导出它们
服务端组件 API
const const result: any
result = Component.render(...)
与客户端组件不同,服务端组件在渲染后没有生命周期 — 它们的全部工作就是创建一些 HTML 和 CSS。因此,其 API 有所不同。
服务端组件暴露了一个 render
方法,可以使用可选的 props 调用它。它返回一个包含 head
、html
和 css
属性的对象,其中 head
包含遇到的任何 <svelte:head>
元素的内容。
你可以使用 svelte/register
直接将 Svelte 组件导入到 Node 中。
var require: NodeRequire
(id: string) => any
require('svelte/register');
const const App: any
App = var require: NodeRequire
(id: string) => any
require('./App.svelte').default;
const { const head: any
head, const html: any
html, const css: any
css } = const App: any
App.render({
answer: number
answer: 42
});
.render()
方法接受以下参数:
参数 | 默认值 | 描述 |
---|---|---|
props |
{} |
要提供给组件的属性对象 |
options |
{} |
选项对象 |
options
对象接受以下选项:
选项 | 默认值 | 描述 |
---|---|---|
context |
new Map() |
要提供给组件的根级上下文键值对的 Map |
const { const head: any
head, const html: any
html, const css: any
css } = App.render(
// props
{ answer: number
answer: 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
代替