use
動作 (Actions) 是在元素掛載時呼叫的函式。它們使用 use:
指令加入,並且通常會使用 $effect
,以便在元素卸載時重設任何狀態。
應用程式
<script>
/** @type {import('svelte/action').Action} */
function myaction(node) {
// the node has been mounted in the DOM
$effect(() => {
// setup goes here
return () => {
// teardown goes here
};
});
}
</script>
<div use:myaction>...</div>
<script lang="ts">
import type { Action } from 'svelte/action';
const myaction: Action = (node) => {
// the node has been mounted in the DOM
$effect(() => {
// setup goes here
return () => {
// teardown goes here
};
});
};
</script>
<div use:myaction>...</div>
可以透過引數呼叫動作
應用程式
<script>
/** @type {import('svelte/action').Action} */
function myaction(node, data) {
// ...
}
</script>
<div use:myaction={data}>...</div>
<script lang="ts">
import type { Action } from 'svelte/action';
const myaction: Action = (node, data) => {
// ...
};
</script>
<div use:myaction={data}>...</div>
動作只會被呼叫一次(但在伺服器端渲染期間不會)— 如果引數變更,它將*不會*再次執行。
舊版模式
在
$effect
符文出現之前,動作可以傳回一個具有update
和destroy
方法的物件,如果引數變更,將會使用最新的引數值呼叫update
。建議使用效果 (effects)。
類型標註
Action
介面接收三個可選的型別引數 — 節點類型(如果動作適用於所有內容,則可以是 Element
)、參數,以及由動作建立的任何自訂事件處理程式。
應用程式
<script>
import { on } from 'svelte/events';
/**
* @type {import('svelte/action').Action<
* HTMLDivElement,
* null,
* {
* onswiperight: (e: CustomEvent) => void;
* onswipeleft: (e: CustomEvent) => void;
* // ...
* }>}
*/
function gestures(node) {
$effect(() => {
// ...
node.dispatchEvent(new CustomEvent('swipeleft'));
// ...
node.dispatchEvent(new CustomEvent('swiperight'));
});
}
</script>
<div
use:gestures
onswipeleft={next}
onswiperight={prev}
>...</div>
<script lang="ts">
import { on } from 'svelte/events';
import type { Action } from 'svelte/action';
const gestures: Action<
HTMLDivElement,
null,
{
onswiperight: (e: CustomEvent) => void;
onswipeleft: (e: CustomEvent) => void = (node) => {
$effect(() => {
// ...
node.dispatchEvent(new CustomEvent('swipeleft'));
// ...
node.dispatchEvent(new CustomEvent('swiperight'));
});
};
</script>
<div
use:gestures
onswipeleft={next}
onswiperight={prev}
>...</div>
上一個 下一個