Skip to main content

Một thành phần có thể thay đổi loại của mình hoàn toàn với <svelte:component>. Trong bài tập này, chúng ta muốn hiển thị RedThing.svelte nếu colorred, GreenThing.svelte nếu là green, và cứ như thế.

Chúng ta có thể làm điều này với một chuỗi các khối if...

App.svelte
{#if selected.color === 'red'}
	<RedThing/>
{:else if selected.color === 'green'}
	<GreenThing/>
{:else if selected.color === 'blue'}
	<BlueThing/>
{/if}

...nhưng nó hơi cồng kềnh. Thay vào đó, chúng ta có thể tạo một thành phần động duy nhất:

App.svelte
<select bind:value={selected}>
	{#each options as option}
		<option value={option}>{option.color}</option>
	{/each}
</select>

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

Giá trị this có thể là bất kỳ hàm tạo thành phần nào, hoặc là một giá trị falsy (undefined, null, false, 0, -0, 0n, NaN) — nếu nó là falsy, không có thành phần nào được hiển thị.

Tiếp theo: <svelte:element>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<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>
 
{#if selected.color === 'red'}
	<RedThing />
{:else}
	<p>TODO khác</p>
{/if}
 
initialising