Client
Creating a component
A client-side component — that is, a component compiled with generate: 'dom'
(or the generate
option left unspecified) is a JavaScript class.
The following initialisation options can be provided:
Existing children of target
are left where they are.
The hydrate
option instructs Svelte to upgrade existing DOM (usually from server-side rendering) rather than creating new elements. It will only work if the component was compiled with the [hydratable: true
option/docs#compile-time-svelte-compile). Hydration of <head>
elements only works properly if the server-side rendering code was also compiled with hydratable: true
, which adds a marker to each element in the <head>
so that the component knows which elements it's responsible for removing during hydration.
Whereas children of target
are normally left alone, hydrate: true
will cause any children to be removed. For that reason, the anchor
option cannot be used alongside hydrate: true
.
The existing DOM doesn't need to match the component — Svelte will 'repair' the DOM as it goes.
$set
Programmatically sets props on an instance. component.$set({ x: 1 })
is equivalent to x = 1
inside the component's <script>
block.
Calling this method schedules an update for the next microtask — the DOM is not updated synchronously.
$on
Causes the callback
function to be called whenever the component dispatches an event
.
A function is returned that will remove the event listener when called.
$destroy
Removes a component from the DOM and triggers any onDestroy
handlers.
Component props
If a component is compiled with accessors: true
, each instance will have getters and setters corresponding to each of the component's props. Setting a value will cause a synchronous update, rather than the default async update caused by component.$set(...)
.
By default, accessors
is false
, unless you're compiling as a custom element.