如何在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:component>

<svelte:component>元件呈现一个动态成分,使用指定为这个属性的组件构造。当属性更改时,组件将被销毁并重新创建。

例如:

<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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章