svelte/attachments
import { function createAttachmentKey(): symbolCreates an object key that will be recognised as an attachment when the object is spread onto an element,
as a programmatic alternative to using {@attach ...}. This can be useful for library authors, though
is generally not needed when building an app.
<script>
import { createAttachmentKey } from 'svelte/attachments';
const props = {
class: 'cool',
onclick: () => alert('clicked'),
[createAttachmentKey()]: (node) => {
node.textContent = 'attached!';
}
};
</script>
<button {...props}>click me</button>
createAttachmentKey, function fromAction<E extends EventTarget, T extends unknown>(action: Action<E, T, Record<never, any>> | ((element: E, arg: T) => void | ActionReturn<T, Record<never, any>>), fn: () => T): Attachment<E> (+1 overload)Converts an action into an attachment keeping the same behavior.
It’s useful if you want to start using attachments on components but you have actions provided by a library.
Note that the second argument, if provided, must be a function that returns the argument to the
action function, not the argument itself.
<!-- with an action -->
<div use:foo={bar}>...</div>
<!-- with an attachment -->
<div {@attach fromAction(foo, () => bar)}>...</div>
fromAction } from 'svelte/attachments';创建附件密钥
自 5.29 起可用
创建一个对象键,当对象被扩展到元素上时,该键将被识别为附件,作为使用{@attach ...}的编程替代方案。这对于库的作者可能很有用,但在构建应用程序时通常不需要。
<script>
import { createAttachmentKey } from 'svelte/attachments';
const props = {
class: 'cool',
onclick: () => alert('clicked'),
[createAttachmentKey()]: (node) => {
node.textContent = 'attached!';
}
};
</script>
<button {...props}>click me</button>function createAttachmentKey(): symbol;从动作
将 操作 转换为 附件,保持相同的行为。如果您想在组件上开始使用附件,但已经有由库提供的操作,这很有用。
请注意,第二个参数(如果提供)必须是一个函数,该函数返回要传递给操作函数的参数,而不是参数本身。
<!-- with an action -->
<div use:foo={bar}>...</div>
<!-- with an attachment -->
<div {@attach fromAction(foo, () => bar)}>...</div>function fromAction<
E extends EventTarget,
T extends unknown
>(
action:
| Action<E, T>
| ((element: E, arg: T) => void | ActionReturn<T>),
fn: () => T
): Attachment<E>;function fromAction<E extends EventTarget>(
action:
| Action<E, void>
| ((element: E) => void | ActionReturn<void>)
): Attachment<E>;附件
一个附件是一个在元素挂载到 DOM 时运行的函数,并且可选地返回一个在元素稍后移除时被调用的函数。
它可以附加到具有 #{@attach ...} 标签的元素上,或者通过扩展一个包含使用 createAttachmentKey 创建的属性的对象。
interface Attachment<T extends EventTarget = Element> {…}(element: T): void | (() => void);Edit this page on GitHub llms.txt