Skip to main content

Execução

svelte/action

Editar esta página na GitHub

As ações são funções que são chamadas quando um elemento é criado. Elas podem retornar um objeto com um método destroy que é chamado depois do elemento ser desmontado:

App.svelte
<script>
	/** @type {import('svelte/action').Action}  */
	function foo(node) {
		// o nó foi montado no DOM

		return {
			destroy() {
				// o nó foi removido do DOM
			}
		};
	}
</script>

<div use:foo />
App.svelte
<script lang="ts">
	import type { Action } from 'svelte/action';
	
	const foo: Action = (node) => {
		// o nó foi montado no DOM
	
		return {
			destroy() {
				// o nó foi removido do DOM
			},
		};
	};
</script>

<div use:foo />

Uma ação pode ter um parâmetro. Se o valor retornado tiver um método update, será chamado imediatamente depois da Svelter ter aplicado atualizações à marcação sempre que este parâmetro mudar.

Não temos que preocupar-nos com o fato de estarmos a redeclarar a função foo para toda instância do componente — a Svelte içará quaisquer funções que não dependem do estado local para fora da definição do componente.

App.svelte
<script>
	/** @type {string} */
	export let bar;

	/** @type {import('svelte/action').Action<HTMLElement, string>}  */
	function foo(node, bar) {
		// o nó foi montado no DOM

		return {
			update(bar) {
				// o valor de `bar` foi mudado
			},

			destroy() {
				// o nó foi removido do DOM
			}
		};
	}
</script>

<div use:foo={bar} />
App.svelte
<script lang="ts">
	import type { Action } from 'svelte/action';
	
	export let bar: string;
	
	const foo: Action<HTMLElement, string> = (node, bar) => {
		// o nó foi montado no DOM
	
		return {
			update(bar) {
				// o valor de `bar` foi mudado
			},
	
			destroy() {
				// o nó foi removido do DOM
			},
		};
	};
</script>

<div use:foo={bar} />

Atributos

Algumas vezes as ações emitem eventos e aplicam atributos personalizados aos elementos nos quais são aplicadas. Para suportar isto, as ações tipadas com o tipo Action ou ActionReturn podem ter um último parâmetro, Attributes:

App.svelte
<script>
	/**
	 * @type {import('svelte/action').Action<HTMLDivElement, { prop: any }, { 'on:emit': (e: CustomEvent<string>) => void }>}
	 */
	function foo(node, { prop }) {
		// o nó foi montado no DOM

		//...LÓGICA
		node.dispatchEvent(new CustomEvent('emit', { detail: 'hello' }));

		return {
			destroy() {
				// o nó foi removido do DOM
			}
		};
	}
</script>

<div use:foo={{ prop: 'someValue' }} on:emit={handleEmit} />
App.svelte
<script lang="ts">
	import type { Action } from 'svelte/action';
	
	const foo: Action<
		HTMLDivElement,
		{ prop: any },
		{ 'on:emit': (e: CustomEvent<string>) => void }
	> = (node, { prop }) => {
		// o nó foi montado no DOM
	
		//...LÓGICA
		node.dispatchEvent(new CustomEvent('emit', { detail: 'hello' }));
	
		return {
			destroy() {
				// o nó foi removido do DOM
			},
		};
	};
</script>

<div use:foo={{ prop: 'someValue' }} on:emit={handleEmit} />

Tipos

Action

Actions are functions that are called when an element is created. You can use this interface to type such actions. The following example defines an action that only works on <div> elements and optionally accepts a parameter which it has a default value for:

ts
export const myAction: Action<HTMLDivElement, { someProperty: boolean } | undefined> = (node, param = { someProperty: true }) => {
// ...
}

Action<HTMLDivElement> and Action<HTMLDiveElement, undefined> both signal that the action accepts no parameters.

You can return an object with methods update and destroy from the function and type which additional attributes and events it has. See interface ActionReturn for more details.

Docs: https://svelte.dev/docs/svelte-action

ts
interface Action<
Element = HTMLElement,
Parameter = undefined,
Attributes extends Record<string, any> = Record<
never,
any
>
> {}
ts
<Node extends Element>(
...args: undefined extends Parameter
? [node: Node, parameter?: Parameter]
: [node: Node, parameter: Parameter]
): void | ActionReturn<Parameter, Attributes>;

ActionReturn

Actions can return an object containing the two properties defined in this interface. Both are optional.

  • update: An action can have a parameter. This method will be called whenever that parameter changes, immediately after Svelte has applied updates to the markup. ActionReturn and ActionReturn<undefined> both mean that the action accepts no parameters.
  • destroy: Method that is called after the element is unmounted

Additionally, you can specify which additional attributes and events the action enables on the applied element. This applies to TypeScript typings only and has no effect at runtime.

Example usage:

ts
interface Attributes {
newprop?: string;
'on:event': (e: CustomEvent<boolean>) => void;
}
export function myAction(node: HTMLElement, parameter: Parameter): ActionReturn<Parameter, Attributes> {
// ...
return {
update: (updatedParameter) => {...},
destroy: () => {...}
};
}

Docs: https://svelte.dev/docs/svelte-action

ts
interface ActionReturn<
Parameter = undefined,
Attributes extends Record<string, any> = Record<
never,
any
>
> {}
ts
update?: (parameter: Parameter) => void;
ts
destroy?: () => void;
anterior svelte/easing