svelte5ダイナミックコンポーネントを使ったテーマ変更 の履歴(No.1)

更新


プログラミング/svelte

svelte5 ではコンポーネント名を動的に決められるのだそうです

通常であれば

<Component>Hello!</Component>

と書くところを、

<theme.Component>Hello!</theme.Component>

と書いていい。

なので、theme にいろいろなコンポーネントを持たせておいて、 動的にその中身を差し替えることでテーマを変更することが可能になる。

LANG:html
<script lang="ts">
	import DefaultComponent from './DefaultComponent.svelte';
	import AlternativeComponent from './AlternativeComponent.svelte';

	// default theme
	const defaultTheme = {Component: DefaultComponent};
	type Theme = typeof defaultTheme;

	// one theme may contain many components

	// default theme
	const alternativeTheme = {Component: AlternativeComponent} satisfies Theme;

	// `satisfies Theme` above confirms each component in alternativeTheme
	// is compatible with the correspondent in the defaultTheme.

	// theme can be easily switched
	let sw = $state(true);
	let theme = $derived(sw ? defaultTheme : alternativeTheme);
</script>

<button onclick={()=> sw = !sw}>
	Tollge Theme
</button>

<theme.Component></theme.Component>

https://svelte-5-preview.vercel.app/#H4sIAAAAAAAACoVTUUvDQAz-K_EQnCDre90mRScI4oNUX5zgrU3d4fWu3GXKGP3v5tq6zq3oW5N835cvuXQrCqXRi_hlK4wsUcQiqSpxIWhThcB_oibk2Nu1y0Jm4jOnKgItzft0IcgvxGxhFqTKyjqCGyzkWtO15dCgISicLeFsHB0Wxq302eUeOeGEM5LUJx4LDBX3RVgms8YT5G2ndIUlwhS2O3R85K5uuodZ4QceAlv8EunUowiYBNQAS7kBbkdSGf42Ieg0_Q795tmtLxT6Vv0tMArlSg8os1VPAeWbgOFLjdDRvxStQjcuOYeeoXmDNU1y3-C4H172WxpawNASazjw2c_bzppJA0tkz17pDXj2la0wDxCNxDH3OPUkCUfk1nh--VOhzsBpjo4b5iOGXv1-nvjIcKBPovbIwmGZyXJNZA3vPtMq-5huR-fTWdv1xH_VzfGlVuv37g0DvaW09MbFuL-niNN80KXNFY-ciziYri929394I3_-DNXsZn6bPN2nk6ia_aU6tPh_lJP7dP74kKR3z_Nh9df6Gyjbkty_AwAA


Counter: 895 (from 2010/06/03), today: 2, yesterday: 3