首页 > 解决方案 > 如何在 Svelte 中动态渲染组件?

问题描述

我正在尝试遍历一个数组以呈现具有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

解决方案


使用<svelte:component>

<svelte:component>元素使用指定为 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


推荐阅读