【问题标题】:How to dynamically render components in Svelte?如何在 Svelte 中动态渲染组件?
【发布时间】:2021-04-15 18:47:41
【问题描述】:

我正在尝试遍历一个数组以呈现具有type 值的组件。

<script>

import One from './One.svelte';    
import Two from './Two.svelte';
import Three from './Three.svelte';

const contents = [
 {type: 'One'},
 {type: 'Two'},
 {type: 'Three'},
 {type: 'One'}
]

</script>

{#each contents as content}
    <{content.type} />
{/each}

期望的输出:

<One />
<Two />
<Three />
<One />

最好的方法是什么?

【问题讨论】:

    标签: svelte


    【解决方案1】:

    使用&lt;svelte:component&gt;:

    &lt;svelte:component&gt; 元素动态呈现组件,使用 指定为 this 属性的组件构造函数。当。。。的时候 属性更改,组件被销毁并重新创建。

    例如:

    <script>
        import One from './One.svelte';    
        import Two from './Two.svelte';
    
    const contents = [
     One,
     Two
    ]
    </script>
    
    {#each contents as content}
        <svelte:component this={content}/>
    {/each}
    

    https://svelte.dev/repl/e56e75ad9b584c44930fe96489a36e14?version=3.31.2

    【讨论】:

      猜你喜欢
      • 2021-12-13
      • 2021-12-11
      • 1970-01-01
      • 2015-09-07
      • 2020-05-10
      • 2019-12-26
      • 2015-05-18
      • 2017-08-17
      • 2021-12-28
      相关资源
      最近更新 更多