Svelte 5中如何通过Attachment实现IFrame响应$state变量更新?
解决Svelte 5中Attachment配合iframe响应式更新的问题
核心思路是在Attachment函数内部创建响应式副作用,同时跟踪iframe的加载状态,确保响应式变量更新时能同步修改iframe内容:
- 在Attachment函数内定义变量存储iframe的body元素引用,让副作用能访问到它
- 监听iframe的
load事件,加载完成后保存body引用并初始化内容 - 使用
$effect监听响应式变量counter的变化,只要变量更新且iframe已加载完成,就同步更新iframe内容
修改后的代码如下:
const myAttachment: Attachment<HTMLIFrameElement> = (iframe) => { let iframeBody: HTMLElement | null = null; // 保存iframe加载后的body引用并初始化内容 iframe.addEventListener('load', () => { iframeBody = iframe.contentDocument?.body ?? null; if (iframeBody) { iframeBody.innerText = `The value from the reactive variable is ${counter}.`; } }); // 监听counter变化,同步更新iframe内容 $effect(() => { if (iframeBody) { iframeBody.innerText = `The value from the reactive variable is ${counter}.`; } }); }
说明
- Attachment函数本身处于响应式上下文,所以可以直接使用
$effect $effect会自动追踪counter的变化,每次counter赋值新值时都会触发副作用函数- 先通过
load事件确保iframe加载完成后再获取body元素,避免操作null引用
内容的提问来源于stack exchange,提问作者Peppe L-G
相关产品推荐
相关产品推荐

