Sveltejs 有条件地渲染 html 属性

Sveltejs render html attribute conditionally

如何使用 svelte 有条件地在 html 元素上呈现属性?需要明确的是,我不是在谈论条件值,而是属性存在本身。

例如,我只想自动对焦此输入列表中的第一项:

{{#each codeInputs as codeInput, index}}
  <input bind:value="inputCodes[index]" type="text" autofocus> 
{{/each}}

属性 autofocus 应该只存在于第一项。我可以使用索引来检测第一项,但是 autofocus="{{index===0}}" 呈现 autofocus="true""false",所以这不是我需要的。

另见 https://github.com/sveltejs/svelte/issues/259

试一试 — it does work。当 Svelte 看到类似 autofocus='{{xyz}} 的内容时,它不会设置 属性 ,它会设置 属性 — 该属性必须是一个字符串(这没有用)而 属性 可以是一个布尔值。