Shorthand 每个 Svelte 块中的属性

Shorthand attribute in each block of Svelte

我有一个 JSON 变量,它包含以下方式的属性:

// JSON variable defining attributes for elements to be created

let myElements = [
    {
        attr1: "myAttr1",
        attr2: "myAttr2",
    },
    {
        attr1: "myAttr4",
        attr2: "myAttr5",
    }
];

我想使用 each 块根据 JSON 变量中定义的属性渲染 HTML 元素,如下所示:

<-- Svelte Code -->

{#each myElements as myElement}
    <div {myElement.attr1} {myElement.attr2}>
    </div>
{/each}

这样它们将以这种方式呈现:

<-- Desired Resultant HTML -->
<div attr1="myAttr1" attr="myAttr2"></div>
<div attr1="myAttr4" attr2="myAttr5"></div>

但是,当我在 HTML 标签中引用 {myElement.attr1} 等属性时,svelte 会显示“Expected a }”错误。可以这样使用 shorthand 属性吗?

你可以使用解构

<script>
    let things = [
    {attr1:'a',attr2:'b'},
        {attr1:'ace',attr2:'bdd'},
        {attr1:'as',attr2:'bsd'},
    ]
</script>

{#each things as {attr1, attr2}}
    <div {attr1} {attr2}>{attr1}</div>
{/each}