codecamp

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>


Svelte <svelte:self>
Svelte <svelte:window>
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录

Svelte module context

Svelte 调试

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }