Skip to main content

use:

在 Svelte 5.29 及更高版本中,请考虑使用 attachments,因为它们更灵活且可组合。

操作是在安装元素时调用的函数。它们是使用 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:

App
<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:

App
<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 符文之前,操作可以返回一个包含 updatedestroy 方法的对象,其中 update 方法将使用参数的最新值进行调用(如果参数值发生变化)。建议使用效果。

类型(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:

App
<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>
上一页 下一页