O pacote svelte expõe as funções do ciclo de vida e a API de contexto.
onMountpermalink
tsfunction onMount<T>(fn: () =>| NotFunction<T>| Promise<NotFunction<T>>| (() => any)): void;
A função onMount agenda uma função de resposta à executar logo que o componente tiver sido montado ao DOM. Esta deve ser chamada durante a inicialização do componente (mas não precisa morar dentro do componente; pode ser chamada a partir dum módulo externo).
onMount não executa dentro dum componente do lado do servidor:
<script>
import { onMount } from 'svelte';
onMount(() => {
console.log('the component has mounted');
});
</script>Se uma função for retornada a partir de onMount, será chamada quando o componente for desmontado:
<script>
import { onMount } from 'svelte';
onMount(() => {
const interval = setInterval(() => {
console.log('beep');
}, 1000);
return () => clearInterval(interval);
});
</script>Este comportamento apenas funcionará quando a função passada à
onMountretornar de maneira síncrona um valor. As funçõesasyncsempre retornam umaPromise, e como tal não podem retornar de maneira síncrona uma função.
beforeUpdatepermalink
tsfunction beforeUpdate(fn: () => void): void;
Agenda uma função de resposta à executar imediatamente antes do componente ser atualizado depois de qualquer mudança.
A primeira vez que a função de resposta executar será antes da
onMountinicial
<script>
import { beforeUpdate } from 'svelte';
beforeUpdate(() => {
console.log('the component is about to update');
});
</script>afterUpdatepermalink
tsfunction afterUpdate(fn: () => void): void;
Agenda uma função de resposta à executar imediatamente depois do componente tiver sido atualizado.
A primeira vez que a função de resposta executar será depois da
onMountinicial
<script>
import { afterUpdate } from 'svelte';
afterUpdate(() => {
console.log('the component just updated');
});
</script>onDestroypermalink
tsfunction onDestroy(fn: () => any): void;
Agenda uma função de resposta à executar imediatamente antes do componente ser desmontado.
Fora a onMount, beforeUpdate, afterUpdate e onDestroy, esta é a única que executa dentro dum componente do lado do servidor:
<script>
import { onDestroy } from 'svelte';
onDestroy(() => {
console.log('the component is being destroyed');
});
</script>tickpermalink
tsfunction tick(): Promise<void>;
Retorna uma promessa que resolve assim que quaisquer mudanças de estado pendentes tiverem sido aplicadas, ou na próxima micro-tarefa se não existirem nenhuma mudança a ser aplicada:
<script>
import { beforeUpdate, tick } from 'svelte';
beforeUpdate(async () => {
console.log('the component is about to update');
await tick();
console.log('the component just updated');
});
</script>setContextpermalink
tsfunction setContext<T>(key: any, context: T): T;
Associa um objeto context arbitrário com o componente atual e a key especificada e retorna este objeto. O contexto está então disponível aos filhos do componente (incluindo conteúdo isolado) com a getContext.
Tal como as funções do ciclo de vida, esta deve ser chamada durante a inicialização do componente:
<script>
import { setContext } from 'svelte';
setContext('answer', 42);
</script>O contexto não é inerentemente reativo. Se precisarmos de valores reativos no contexto então podemos passar uma memória ao contexto, que será reativo.
getContextpermalink
tsfunction getContext<T>(key: any): T;
Recupera o contexto que pertence ao componente pai mais próximo com a key especificada. Deve ser chamada durante a inicialização do componente:
<script>
import { getContext } from 'svelte';
const answer = getContext('answer');
</script>hasContextpermalink
tsfunction hasContext(key: any): boolean;
Verifica se uma dada key foi definida no contexto dum componente pai. Deve ser chamada durante a inicialização do componente:
<script>
import { hasContext } from 'svelte';
if (hasContext('answer')) {
// fazer algo
}
</script>getAllContextspermalink
tsfunction getAllContexts<T extends Map<any, any> = Map<any, any>>(): T;
Recupera o mapa do contexto inteiro que pertence ao componente pai mais próximo. Deve ser chamada durante a inicialização do componente. Útil, por exemplo, se criarmos programaticamente um componente e quisermos passar o contexto existente à ele:
<script>
import { getAllContexts } from 'svelte';
const contexts = getAllContexts();
</script>createEventDispatcherpermalink
tsfunction createEventDispatcher<EventMap extends Record<string, any> = any>(): EventDispatcher<EventMap>;
Cria um despachador de evento que pode ser usado para despachar eventos do componente. Os despachadores de evento são funções que podem receber dois argumentos name e detail.
Os eventos do componente criados com createEventDispatcher criam um CustomEvent. Estes eventos não transbordam. O argumento detail corresponde à propriedade CustomEvent.detail e pode conter qualquer tipo de dado:
<script>
import { createEventDispatcher } from 'svelte';
const dispatch = createEventDispatcher();
</script>
<button on:click={() => dispatch('notify', 'detail value')}>Fire Event</button>Os eventos despachados a partir dos componentes filhos podem ser ouvidos nos seus pais. Qualquer dado fornecido quando o evento foi despachado está disponível na propriedade detail do objeto do evento:
<script>
function callbackFunction(event) {
console.log(`Notify fired! Detail: ${event.detail}`);
}
</script>
<Child on:notify={callbackFunction} />Os eventos podem ser canceláveis passando um terceiro parâmetro à função de despacho. A função retorna false se o evento for cancelado com event.preventDefault(), de outro modo retorna true:
<script>
import { createEventDispatcher } from 'svelte';
const dispatch = createEventDispatcher();
function notify() {
const shouldContinue = dispatch('notify', 'detail value', { cancelable: true });
if (shouldContinue) {
// ninguém chamou `preventDefault`
} else {
// um ouvinte chamou `preventDefault`
}
}
</script>Nós podemos tipificar o despachador de evento para definir quais eventos pode receber. Isto tornará o nosso código mais seguro no que diz respeito a tipo tanto dentro do componente (chamadas erradas são sinalizadas) como quando usarmos o componente (tipos de eventos agora são reduzidos). Consulte neste material como fazer isto.
Tipospermalink
ComponentConstructorOptionspermalink
Svelte components were classes in Svelte 4. In Svelte 5, thy are not anymore. Use
mountorcreateRootinstead to instantiate components. See breaking changes for more info.
tsinterface ComponentConstructorOptions<Props extends Record<string, any> = Record<string, any>> {…}
tstarget: Element | Document | ShadowRoot;
tsanchor?: Element;
tsprops?: Props;
tscontext?: Map<any, any>;
tshydrate?: boolean;
tsintro?: boolean;
ts$$inline?: boolean;
ComponentEventspermalink
Convenience type to get the events the given component expects. Example:
<script lang="ts">
import type { ComponentEvents } from 'svelte';
import Component from './Component.svelte';
function handleCloseEvent(event: ComponentEvents<Component>['close']) {
console.log(event.detail);
}
</script>
<Component on:close={handleCloseEvent} />tstype ComponentEvents<Comp extends SvelteComponent> =Comp extends SvelteComponent<any, infer Events>? Events: never;
ComponentPropspermalink
Convenience type to get the props the given component expects. Example:
<script lang="ts">
import type { ComponentProps } from 'svelte';
import Component from './Component.svelte';
const props: ComponentProps<Component> = { foo: 'bar' }; // Errors if these aren't the correct props
</script>tstype ComponentProps<Comp extends SvelteComponent> =Comp extends SvelteComponent<infer Props> ? Props : never;
ComponentTypepermalink
Convenience type to get the type of a Svelte component. Useful for example in combination with
dynamic components using <svelte:component>.
Example:
<script lang="ts">
import type { ComponentType, SvelteComponent } from 'svelte';
import Component1 from './Component1.svelte';
import Component2 from './Component2.svelte';
const component: ComponentType = someLogic() ? Component1 : Component2;
const componentOfCertainSubType: ComponentType<SvelteComponent<{ needsThisProp: string }>> = someLogic() ? Component1 : Component2;
</script>
<svelte:component this={component} />
<svelte:component this={componentOfCertainSubType} needsThisProp="hello" />tstype ComponentType<Comp extends SvelteComponent = SvelteComponent> = (new (options: ComponentConstructorOptions<Comp extends SvelteComponent<infer Props>? Props: Record<string, any>>) => Comp) & {/** The custom element version of the component. Only present if compiled with the `customElement` compiler option */element?: typeof HTMLElement;};
EventDispatcherpermalink
tsinterface EventDispatcher<EventMap extends Record<string, any>> {…}
ts<Type extends keyof EventMap>(...args: null extends EventMap[Type]? [type: Type, parameter?: EventMap[Type] | null | undefined, options?: DispatchOptions]: undefined extends EventMap[Type]? [type: Type, parameter?: EventMap[Type] | null | undefined, options?: DispatchOptions]: [type: Type, parameter: EventMap[Type], options?: DispatchOptions]): boolean;
Snippetpermalink
The type of a #snippet block. You can use it to (for example) express that your component expects a snippet of a certain type:
tslet {banner } =$props <{banner :Snippet <{text : string }> }>();
You can only call a snippet through the {@render ...} tag.
tsinterface Snippet<T = void> {…}
ts(arg: T): typeof SnippetReturn & {_: 'functions passed to {@render ...} tags must use the `Snippet` type imported from "svelte"';};
SvelteComponentpermalink
Can be used to create strongly typed Svelte components.
Example:permalink
You have component library on npm called component-library, from which
you export a component called MyComponent. For Svelte+TypeScript users,
you want to provide typings. Therefore you create a index.d.ts:
ts
Typing this makes it possible for IDEs like VS Code with the Svelte extension to provide intellisense and to use the component like this in a Svelte file with TypeScript:
<script lang="ts">
import { MyComponent } from "component-library";
</script>
<MyComponent foo={'bar'} />This was the base class for Svelte components in Svelte 4. Svelte 5+ components
are completely different under the hood. You should only use this type for typing,
not actually instantiate components with new - use mount or createRoot instead.
See breaking changes
for more info.
tsclass SvelteComponent<Props extends Record<string, any> = any,Events extends Record<string, any> = any,Slots extends Record<string, any> = any> {…}
ts[prop: string]: any;
tsconstructor(options: ComponentConstructorOptions<PropsWithChildren<Props, Slots>>);
- deprecated This constructor only exists when using the
asClassComponentcompatibility helper, which is a stop-gap solution. Migrate towards usingmountorcreateRootinstead. See https://svelte-5-preview.vercel.app/docs/breaking-changes#components-are-no-longer-classes for more info.
ts$destroy(): void;
- deprecated This method only exists when using one of the legacy compatibility helpers, which is a stop-gap solution. See https://svelte-5-preview.vercel.app/docs/breaking-changes#components-are-no-longer-classes for more info.
ts$on<K extends Extract<keyof Events, string>>(type: K,callback: (e: Events[K]) => void): () => void;
- deprecated This method only exists when using one of the legacy compatibility helpers, which is a stop-gap solution. See https://svelte-5-preview.vercel.app/docs/breaking-changes#components-are-no-longer-classes for more info.
ts$set(props: Partial<Props>): void;
- deprecated This method only exists when using one of the legacy compatibility helpers, which is a stop-gap solution. See https://svelte-5-preview.vercel.app/docs/breaking-changes#components-are-no-longer-classes for more info.
SvelteComponentTypedpermalink
Use
SvelteComponentinstead. See TODO for more information.
tsclass SvelteComponentTyped<Props extends Record<string, any> = any,Events extends Record<string, any> = any,Slots extends Record<string, any> = any