Sveltesveltecomponent

Svelte <svelte:component>

一个组件可以用 ​<svelte:component>​ 改变它的类别。而不是一系列 ​if​ 块......{#if selected.color === 'red'}

<RedThing/>

{:else if selected.color === 'green'}

<GreenThing/>

{:else if selected.color === 'blue'}

<BlueThing/>

{/if}...我们可以有一个动态组件:<svelte:component this={selected.component}/>​this​ 值可以是任何组件构造函数,也可以是 falsy 值——如果它是 falsy,则不会呈现任何组件。示例代码App.svelte<script>

import RedThing from './RedThing.svelte';

import GreenThing from './GreenThing.svelte';

import BlueThing from './BlueThing.svelte';

const options = [

{ color: 'red', component: RedThing },

{ color: 'green', component: GreenThing },

{ color: 'blue', component: BlueThing },

];

let selected = options[0];

</script>

<select bind:value={selected}>

{#each options as option}

<option value={option}>{option.color}</option>

{/each}

</select>

<svelte:component this={selected.component}/>BlueThing.svelte<style>

strong { color: blue; }

</style>

<strong>blue thing</strong>GreenThing.svelte<style>

strong { color: green; }

</style>

<strong>green thing</strong>RedThing.svelte<style>

strong { color: red; }

</style>

<strong>red thing</strong>