LoginSignup
2
0

More than 3 years have passed since last update.

Svelte3 svelte:componentでコンポーネントを動的にレンダリングする

Posted at

プルダウンで選択した内容によってコンポーネントを動的に書き換えたい、みたいな時のやり方。

参考リンク

ソース

<select bind:value="{selected}">
    {#each options as option}
        <option value="{option}">{option.name}</option>
    {/each}
</select>

<!-- ここが動的にレンダリングされる -->
<svelte:component this="{selected.component}"/>

<script>
    import Hoge1 from './Hoge1.svelte';
    import Hoge2 from './Hoge2.svelte';
    import Hoge3 from './Hoge3.svelte';

    const options = [
        { name: '', component: null },
        { name: 'hoge1', component: Hoge1 },
        { name: 'hoge2', component: Hoge2 },
        { name: 'hoge3', component: Hoge3 },
    ];
    let selected = options[0];
</script>

thisにコンポーネント以外を渡した場合

nullとかfalseとかとか...。
コンポーネント以外を渡すとなにもレンダリングされません。

前にレンダリングされていたコンポーネントがある場合、前のコンポーネントが破棄されるだけです。

プロパティを渡す

特別なことはなく普通に渡すだけ。

<svelte:component this="{selected.component}" fuga="{selected.name}"/>
2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0