简体   繁体   English

Svelte 的每个块中的速记属性

[英]Shorthand attribute in each block of Svelte

I have a JSON variable which contains attributes in the following manner:我有一个 JSON 变量,它包含以下方式的属性:

// JSON variable defining attributes for elements to be created

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

I want to render HTML elements based on the attributes defined in the JSON variable using the each block as shown below:我想根据 JSON 变量中定义的属性使用 each 块呈现 HTML 元素,如下所示:

<-- Svelte Code -->

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

So that they will be rendered in this way:以便它们以这种方式呈现:

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

However, svelte shows an "Expected a }" error when I refer to attributes like {myElement.attr1} in an HTML tag.但是,当我在 HTML 标记中引用{myElement.attr1}等属性时,svelte 会显示“预期为 }”错误。 Is it possible to use the shorthand attributes in this way?是否可以以这种方式使用速记属性?

you could use deconstruction你可以使用解构

<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}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM