命令式元件 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: {
// assuming App.svelte contains something like
// `export let answer`:
answer: number
answer: 42
}
});
可以提供以下初始化選項
選項 | 預設值 | 描述 |
---|---|---|
target |
無 | 要渲染到的 HTMLElement 或 ShadowRoot 。此選項為必填 |
anchor |
null |
要在其之前立即渲染元件的 target 的子元素 |
props |
{} |
要提供給元件的屬性物件 |
context |
new Map() |
要提供給元件的根級別 context 鍵值對 Map |
hydrate |
false |
請參閱下方 |
intro |
false |
如果為 true ,將在初始渲染時播放過渡,而不是等待後續的狀態變更 |
target
的現有子元素會保留在其位置。
hydrate
選項指示 Svelte 升級現有的 DOM(通常來自伺服器端渲染),而不是建立新的元素。它僅在元件使用 hydratable: true
選項編譯時才有效。如果伺服器端渲染程式碼也使用 hydratable: true
編譯,<head>
元素的 hydration 才能正確運作,這會將標記新增至 <head>
中的每個元素,以便元件知道負責在 hydration 期間移除哪些元素。
雖然 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; }
function $state<{ answer: number; }>(initial: { answer: number; }): { answer: number; } (+1 overload) namespace $state
$state({Declares reactive state.
Example:
let count = $state(0);
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
元件 props
component.prop;
component.prop = value;
如果元件使用 accessors: true
編譯,則每個實例都會有與元件的每個 props 對應的 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
物件接受以下選項
選項 | 預設值 | 描述 |
---|---|---|
context |
new Map() |
要提供給元件的根級別 context 鍵值對 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