A component can change its category altogether with <svelte:component>
. Instead of a sequence of if
blocks...
{#if selected.color === 'red'}
<RedThing/>
{:else if selected.color === 'green'}
<GreenThing/>
{:else if selected.color === 'blue'}
<BlueThing/>
{/if}
...we can have a single dynamic component:
<svelte:component this={selected.component}/>
The this
value can be any component constructor, or a falsy value — if it's falsy, no component is rendered.
App.svelte
BlueThing.svelte
GreenThing.svelte
RedThing.svelte
xxxxxxxxxx
27
1
<script>
2
import RedThing from './RedThing.svelte';
3
import GreenThing from './GreenThing.svelte';
4
import BlueThing from './BlueThing.svelte';
5
6
const options = [
7
{ color: 'red', component: RedThing },
8
{ color: 'green', component: GreenThing },
9
{ color: 'blue', component: BlueThing },
10
];
11
12
let selected = options[0];
13
</script>
14
15
<select bind:value={selected}>
16
{#each options as option}
17
<option value={option}>{option.color}</option>
18
{/each}
19
</select>
20
Console
xxxxxxxxxx
322
1
/* App.svelte generated by Svelte v3.23.2 */
2
import {
3
SvelteComponent,
4
add_render_callback,
5
append,
6
check_outros,
7
create_component,
8
destroy_component,
9
destroy_each,
10
detach,
11
element,
12
empty,
13
group_outros,
14
init,
15
insert,
16
listen,
Compiler options
result = svelte.compile(source, {
generate:
});xxxxxxxxxx
1
1
/* Add a <style> tag to see compiled CSS */