如何在 Svelte 中动态渲染组件? [英] How to dynamically render components in Svelte?
本文介绍了如何在 Svelte 中动态渲染组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试遍历一个数组以呈现具有 type
值的组件.
Im trying to loop through an array to render the component with the value of 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 />
最好的方法是什么?
推荐答案
使用
:
元素动态呈现组件,使用指定为 this 属性的组件构造函数.当...的时候属性发生变化,组件被销毁并重新创建.
The
<svelte:component>
element renders a component dynamically, using the component constructor specified as the this property. When the property 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}
这篇关于如何在 Svelte 中动态渲染组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文