Svelte <svelte:component>

2023-02-22 16:03 更新

一個組件可以用 ?<svelte:component>? 改變它的類別。而不是一系列 ?if? 塊......

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

...我們可以有一個動態(tài)組件:

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

?this? 值可以是任何組件構造函數(shù),也可以是 falsy 值——如果它是 falsy,則不會呈現(xiàn)任何組件。

示例代碼

  • 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>


以上內容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號