关于 svelte-template-directives
svelte-template-directives 是 Svelte 模板指令参考技能,重点介绍 Svelte 5.29 及以上版本的 attachment,帮助开发者选择响应式 DOM 操作方式并使用模板功能。
主要功能
- 01@attach 使用模式
- 02指令用途速查
- 03与 use: action 的比较
- 04渲染与调试标签指南
- 05带键 each 块指南
适用场景
- 01应用响应式 DOM 行为
- 02选择 @attach 或 use:
- 03渲染片段或原始 HTML
- 04检查标记声明与迭代
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ spences10/ skills --skill svelte-template-directives安装后在 Claude Code 中输入/svelte-template-directives确认已加载。
附带文件references/attach-patterns.mdreferences/other-directives.md
详细介绍
Svelte 模板指令
@attach(Svelte 5.29+)
**use: actions 的响应式替代方案。**依赖项发生变化时会重新运行,可通过展开传递给组件,并支持清理函数。
<script>
import ImageZoom from 'js-image-zoom';
function useZoom(options) {
return (element) => {
new ImageZoom(element, options);
return () => console.log('cleanup');
};
}
</script>
<figure {@attach useZoom({ width: 400 })}>
<img src="photo.jpg" alt="zoomable" />
</figure>
快速参考
| 指令 | 用途 | 响应式? |
|---|---|---|
{@attach} | DOM 操作、第三方集成 | 是 |
{@html} | 渲染原始 HTML 字符串 | 是 |
{@render} | 渲染片段 | 是 |
{let ...} / {const ...} | 在标记中声明局部变量 | 不适用 |
{@debug} | 值发生变化时暂停调试器 | 不适用 |
{#each (key)} | 键控迭代(始终使用 key!) | 是 |
<svelte:window> | Window 事件监听器 | 不适用 |
@attach 与 use: Actions 的比较
| 特性 | use: | @attach |
|---|---|---|
| 参数变化时重新运行 | 否 | 是 |
| 可组合 | 有限 | 完全支持 |
| 传递 props | 手动 | 通过展开自动传递 |
| 转换旧版实现 | 不适用 | fromAction() |
参考文件
- attach-patterns.md - @attach 的实际示例
- other-directives.md - @html、@render、 声明标签、@debug
注意事项
@attach需要 Svelte 5.29+- 使用
svelte/attachments中的fromAction转换旧版 actions - 展开 props 时,Attachment 会通过包装组件传递
- 始终使用带键的 each 块;切勿将索引用作 key
- 全局事件请使用
<svelte:window>/<svelte:document>,不要使用$effect - 使用
{const ...}/{let ...}声明标签来声明标记中的局部变量;{@const ...}是旧版语法。 - **最后验证时间:**2026-05-31
评论
支持 Markdown