如何在Svelte中动态渲染组件?

2024-03-12

我试图循环遍历一个数组来渲染具有以下值的组件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 />

做这个的最好方式是什么?


Use <svelte:component>:

The <svelte:component>element 动态渲染组件,使用 指定为 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 https://svelte.dev/repl/e56e75ad9b584c44930fe96489a36e14?version=3.31.2

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在Svelte中动态渲染组件? 的相关文章

随机推荐