跳至主要內容

svelte/action

Action

Actions 是在元素建立時呼叫的函式。您可以使用此介面來為這些 actions 設定類型。以下範例定義了一個僅適用於 <div> 元素的 action,並可選擇性地接受一個具有預設值的參數

export const 
const myAction: Action<HTMLDivElement, {
    someProperty: boolean;
} | undefined>
myAction
: type Action = /*unresolved*/ anyAction<HTMLDivElement, { someProperty: booleansomeProperty: boolean } | undefined> = (node: anynode,
param: {
    someProperty: boolean;
}
param
= { someProperty: booleansomeProperty: true }) => {
// ... }

Action<HTMLDivElement>Action<HTMLDivElement, undefined> 都表示該 action 不接受任何參數。

您可以從函式返回一個具有 updatedestroy 方法的物件,並設定它所擁有的額外屬性和事件類型。有關更多詳細資訊,請參閱介面 ActionReturn

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

ActionReturn

Actions 可以返回一個包含此介面中定義的兩個屬性的物件。兩者都是可選的。

  • update: action 可以有一個參數。每當該參數更改時,此方法將在 Svelte 將更新應用於標記後立即調用。ActionReturnActionReturn<undefined> 都表示該 action 不接受任何參數。
  • destroy: 在元素卸載後調用的方法

此外,您可以指定 action 在套用的元素上啟用的其他屬性和事件。這僅適用於 TypeScript 的類型定義,在執行時沒有任何影響。

使用範例

interface Attributes {
	Attributes.newprop?: string | undefinednewprop?: string;
	'on:event': (e: CustomEvent<boolean>e: interface CustomEvent<T = any>CustomEvent<boolean>) => void;
}

export function function myAction(node: HTMLElement, parameter: Parameter): ActionReturn<Parameter, Attributes>myAction(node: HTMLElementnode: HTMLElement, parameter: Parameterparameter: type Parameter = /*unresolved*/ anyParameter): type ActionReturn = /*unresolved*/ anyActionReturn<type Parameter = /*unresolved*/ anyParameter, Attributes> {
	// ...
	return {
		update: (updatedParameter: any) => voidupdate: (updatedParameter: anyupdatedParameter) => {...},
		destroy: () => {...}
	};
}
interface ActionReturn<
	Parameter = undefined,
	Attributes extends Record<string, any> = Record<
		never,
		any
	>
> {}
update?: (parameter: Parameter) => void;
destroy?: () => void;

在 GitHub 上編輯此頁面

上一個 下一個