svelte5ダイナミックコンポーネントを使ったテーマ変更 の履歴(No.1)
更新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>
Counter: 1207 (from 2010/06/03),
today: 1,
yesterday: 2