命令型コンポーネント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() |
コンポーネントに提供するルートレベルのコンテキストキーと値のペアの`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);
インスタンスにプログラムでプロパティを設定します。 `component.$set({ x: 1 })`は、コンポーネントの`<script>`ブロック内の`x = 1`と同等です。
このメソッドを呼び出すと、次のマイクロタスクの更新がスケジュールされます。DOMは*同期的に*更新されません。
component.$set({ answer: number
answer: 42 });
Svelte 5+では、代わりに`$state`を使用してコンポーネントのプロパティを作成および更新してください
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+では、代わりにコールバックプロパティを渡してください
$destroy
component.$destroy();
DOMからコンポーネントを削除し、`onDestroy`ハンドラーをトリガーします。
Svelte 5+では、代わりに`unmount`を使用してください
コンポーネントのプロパティ
component.prop;
component.prop = value;
コンポーネントが`accessors: true`でコンパイルされている場合、各インスタンスはコンポーネントのプロパティそれぞれに対応するゲッターとセッターを持ちます。値を設定すると、`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`メソッドを公開します。 `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() |
コンポーネントに提供するルートレベルのコンテキストキーと値のペアの`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`を使用してください