gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 02:46:00 26 4
gpt4 key购买 nike

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

The <svelte:component> element renders a component dynamically, usingthe component constructor specified as the this property. When theproperty changes, the component is destroyed and recreated.

例如:

<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

关于svelte - 如何在 Svelte 中动态渲染组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65656481/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com