use:
操作是在安装元素时调用的函数。它们是使用 use:
指令添加的,并且通常使用 $effect
,以便它们可以在卸载元素时重置任何状态:
¥Actions are functions that are called when an element is mounted. They are added with the use:
directive, and will typically use an $effect
so that they can reset any state when the element is unmounted:
<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>
可以使用参数调用操作:
¥An action can be called with an argument:
<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>
该操作仅调用一次(但不是在服务器端渲染期间) - 如果参数发生变化,它将不会再次运行。
¥The action is only called once (but not during server-side rendering) — it will not run again if the argument changes.
Legacy mode
在
$effect
符文之前,操作可以返回具有update
和destroy
方法的对象,其中如果参数发生变化,将使用参数的最新值调用update
。最好使用效果。¥[!LEGACY] Prior to the
$effect
rune, actions could return an object withupdate
anddestroy
methods, whereupdate
would be called with the latest value of the argument if it changed. Using effects is preferred.
类型(Typing)
¥Typing
Action
接口接收三个可选类型参数 — 节点类型(如果操作适用于所有内容,则可以是 Element
)、参数以及由操作创建的任何自定义事件处理程序:
¥The Action
interface receives three optional type arguments — a node type (which can be Element
, if the action applies to everything), a parameter, and any custom event handlers created by the action:
<script>
/**
* @type {import('svelte/action').Action<
* HTMLDivElement,
* undefined,
* {
* 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 type { Action } from 'svelte/action';
const gestures: Action<
HTMLDivElement,
undefined,
{
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>