Skip to main content

运行时

svelte/action

操作是创建元素时调用的函数。 它们可以使用 destroy 方法返回一个对象,该方法在卸载元素后调用:

Actions are functions that are called when an element is created. They can return an object with a destroy method that is called after the element is unmounted:

<script>
	/** @type {import('svelte/action').Action}  */
	function foo(node) {
		// the node has been mounted in the DOM

		return {
			destroy() {
				// the node has been removed from the DOM
			}
		};
	}
</script>

<div use:foo />

一个动作可以有一个参数。 如果返回值具有 update 方法,则只要该参数发生更改,Svelte 将更新应用到标记后就会立即调用该方法。

An action can have a parameter. If the returned value has an update method, it will be called immediately after Svelte has applied updates to the markup whenever that parameter changes.

不要担心我们会为每个组件实例重新声明 foo 函数 — Svelte 会将任何不依赖于本地状态的函数提升到组件定义之外。

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

	/** @type {import('svelte/action').Action<HTMLElement, string>}  */
	function foo(node, bar) {
		// the node has been mounted in the DOM

		return {
			update(bar) {
				// the value of `bar` has changed
			},

			destroy() {
				// the node has been removed from the DOM
			}
		};
	}
</script>

<div use:foo={bar} />

属性(Attributes)

有时,操作会发出自定义事件并将自定义属性应用到它们所应用到的元素。 为了支持这一点,使用 ActionActionReturn 类型键入的操作可以有最后一个参数 Attributes

Sometimes actions emit custom events and apply custom attributes to the element they are applied to. To support this, actions typed with Action or ActionReturn type can have a last parameter, Attributes:

<script>
	/**
	 * @type {import('svelte/action').Action<HTMLDivElement, { prop: any }, { 'on:emit': (e: CustomEvent<string>) => void }>}
	 */
	function foo(node, { prop }) {
		// the node has been mounted in the DOM

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

		return {
			destroy() {
				// the node has been removed from the DOM
			}
		};
	}
</script>

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

类型(Types)

类型: svelte/action

上一页 svelte/easing
下一页 svelte/compiler