You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将数组元素传递给Svelte的use指令?

解决Svelte中动态绑定Popper动作的问题

你遇到的核心问题是Svelte的use:指令语法错误——当动作是动态值(比如通过数组索引获取的函数)时,必须用use={}的形式包裹,而不是直接写use:表达式。

修正后的基础写法

把原来的use:popperData[i].popperRef改成use={popperData[i].popperRef},完整代码如下:

{#each labeledText as { text, chunk_i }, i}
  <span use={popperData[i].popperRef}>
    {text}
    <!-- 渲染对应的弹窗内容 -->
    {#if popperData[i].popperContent.isOpen}
      <div use={popperData[i].popperContent}>
        弹窗内容(chunk_i: {chunk_i})
      </div>
    {/if}
  </span>
{/each}

更清晰的优化写法

为了避免数组索引带来的潜在问题,可以把labeledText的元素和对应的Popper动作合并成一个数组,遍历的时候直接解构使用:

$: popperItems = labeledText.map(el => {
  const [popperRef, popperContent] = createPopperActions({
    placement: 'top-end',
    strategy: 'fixed'
  });
  return { ...el, popperRef, popperContent };
});

然后在模板中遍历这个合并后的数组:

{#each popperItems as { text, chunk_i, popperRef, popperContent } (chunk_i)}
  <span use={popperRef}>
    {text}
    {#if popperContent.isOpen}
      <div use={popperContent}>
        弹窗内容(chunk_i: {chunk_i})
      </div>
    {/if}
  </span>
{/each}

额外优化:避免不必要的Popper实例重建

如果labeledText是动态更新的,给each循环加上唯一key(比如chunk_i),可以防止每次数组变化时销毁重建所有Popper实例:

{#each labeledText as { text, chunk_i }, i (chunk_i)}
  <!-- 内容同上 -->
{/each}

内容的提问来源于stack exchange,提问作者wildfluss

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 11:38:14